#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME};#end
#parse("File Header.java")
import java.sql.*;
public class BaseDao {
private String driver = "com.mysql.cj.jdbc.Driver";
private String url = "jdbc:mysql://localhost:3306/${database}?serverTimezone=Asia/Shanghai";
private String user = "${user}";
private String pwd = "${password}";
public Connection conn = null;
public PreparedStatement pstmt = null;
public ResultSet rs=null;
//获取连接
public Connection getConnection() {
try {
//如果你没有conn 或者 conn是关闭的时候 就重新获取
if (conn == null || conn.isClosed()) {
//1.加载驱动
Class.forName(driver);
//2.创建conn
conn = DriverManager.getConnection(url, user, pwd);
}
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
//关闭所有连接
public void closeAll(ResultSet rs, PreparedStatement pstmt, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public int executeUpdate(String sql, Object...objects){
try {
conn=getConnection();
pstmt=conn.prepareStatement(sql);
if (objects!=null){
for (int i = 0; i < objects.length; i++) {
pstmt.setObject(i+1,objects[i]);
}
}
return pstmt.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
closeAll(null,pstmt,conn);
}
return 0;
}
}
BaseDao模板
于 2024-07-30 19:45:43 首次发布