本章節(jié)由北京北大青鳥學(xué)校學(xué)術(shù)部講師提供:
package com.jspbbs.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ConnectionManager {
private static final String DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private static final String URL = "jdbc:sqlserver://localhost:1433;DatabaseName=數(shù)據(jù)庫名稱";
private static final String USER = "用戶名";
private static final String PASS = "密碼";
/**
* 獲取數(shù)據(jù)庫連接對象(北京北大青鳥學(xué)校)
*
* @return
*/
public static Connection getConnection() {
Connection connection = null;
try {
Class.forName(DRIVER);
connection = DriverManager.getConnection(URL, USER, PASS);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return connection;
}
/**
* 關(guān)閉數(shù)據(jù)庫相關(guān)對象
* @param conn 數(shù)據(jù)庫連接對象
* @param ps Statement對象
* @param resultSet 數(shù)據(jù)庫結(jié)果集(北京北大青鳥學(xué)校)
*/
public static void closeAll(Connection conn, Statement ps,
ResultSet resultSet) {
try {
if(resultSet!=null){
resultSet.close();
}
if(ps!=null){
ps.close();
}
if(conn!=null && !conn.isClosed()){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
北京北大青鳥學(xué)校