package sql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class BaseDao {
// 连接字符串
private static String URL = "jdbc:sqlserver://localhost:1433;DatabaseName=TestDB";
// 用户名
private static String USER = "sa";
// 密码
private static String PWD = "123";
// SQL连接对象
protected static Connection conn = null;
// 预处理SQL语句对象
protected static PreparedStatement pstmt = null;
// 静态代码块,加载SQLServer驱动
static {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
// 获取连接对象
protected static Connection getConnection() {
try {
return DriverManager.getConnection(URL, USER, PWD);
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
// 关闭SQL相关的对象,释放资源空间
protected static void closeAll(Connection conn, Statement stmt, ResultSet rs) {
try {
if (conn != null) {
conn.close();
}
if (stmt != null) {
stmt.close();
}
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
// 执行数据库操作,执行后返回的Object进行强制转换
protected static Object execute(String sql, Object... objs) {
boolean flag = false;
try {
handle(sql, objs);
flag = pstmt.execute();
return flag ? pstmt.getResultSet() : pstmt.getUpdateCount();
} catch (SQLException e) {
e.printStackTrace();
return null;
} finally {
if (!flag)
closeAll(conn, pstmt, null);
}
}
// 抽取处理操作的相同代码块
private static void handle(String sql, Object[] objs) throws SQLException {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
if (objs != null) {
for (int i = 0; i < objs.length; i++) {
pstmt.setObject(i + 1, objs[i]);
}
}
}
}