public class Basedao {
static{
//加载驱动
try {
Class .forName("com.mysql.cj.jdbc.Driver");//加载驱动程序
} catch (ClassNotFoundException e) { //捕捉驱动类未找到异常
e.printStackTrace();//输出异常信息
}
}
public static Connection getconn(){
//创建一个连接对象
Connection conn=null;
try {
conn= DriverManager.getConnection("jdbc:mysql://localhost:8080/mall?useSSL=false&serverTimezone=UTC","root","123456");//连接数据库路径,用户名,密码
} catch (SQLException e) {
e.printStackTrace();
}
return conn;//返回获取到的数据库连接对象
}
public static int executeIUD(String sql ,Object[] params){
int count=0;
Connection conn=Basedao.getconn(); //连接数据库
//准备SQL
PreparedStatement ps =null;
//insert into user("""","")value(?,?,?)
try {
//准备SQL
ps=conn.prepareStatement(sql); //创建语句
//遍历参数
for (int i=0;i<params.length;i++){
ps.setObject(i+1,params);
}
count= ps.executeUpdate();
} catch (SQLException e) {
//TODO Auto-generated catch block;自动生成的捕获块
e.printStackTrace();
}finally {
Basedao.closeall(null,ps,conn);
}
return count;
}
public static void closeall(ResultSet rs,PreparedStatement ps,Connection conn){
//如果结果集不为空,把结果集关闭
try {
if (rs != null)
rs.close();
//如果预处理对象不为空,把预处理对象
if (ps != null)
ps.close();
//如果连接对象不为空,那么把连接对象关掉
if (conn != null)
conn.close();
}catch (SQLException e) {
e.printStackTrace();
}
}
}
连接数据库Connection
最新推荐文章于 2025-03-01 15:43:14 发布