public class BaseDao {
private String driver = "com.mysql.jdbc.Driver";
private String url = "jdbc:mysql://localhost:3306/mydb";
private String user = "";
private String password = "";
Connection conn = null;
/**
* 获取数据库链接对象
*/
public Connection getConnection(){
if(conn == null){
try {
Class.forName(driver);
conn = DriverManager.getConnection(url,user,password);
} catch (Exception e) {
e.printStackTrace();
}
}
return conn;
}
/**
* 增、删、改操作
*/
public int executeUpdate(String sql, Object[] params){
PreparedStatement pstmt = null;
int num = 0;
conn = getConnection();
try {
pstmt = conn.prepareStatement(sql);
if (params != null) {
for (int i = 0; i < params.length; i++) {
pstmt.setObject(i+1, params[i]);
}
}
num = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally{
closeAll(conn,pstmt, null);
}
}
/**
* 关闭数据库链接
*/
public void closeAll(Connection conn, Statement stmt, ResultSet rs){
if (rs != null) {
try {
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
JDBC 链接案例—— 纯代码,无连接池
最新推荐文章于 2023-03-13 22:42:47 发布