本章节由北京北大青鸟学校学术部讲师提供:
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=数据库名称";
private static final String USER = "用户名";
private static final String PASS = "密码";
/**
* 获取数据库连接对象(北京北大青鸟学校)
*
* @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;
}
/**
* 关闭数据库相关对象
* @param conn 数据库连接对象
* @param ps Statement对象
* @param resultSet 数据库结果集(北京北大青鸟学校)
*/
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();
}
}
}
北京北大青鸟学校