集数据库连接,查询,更新(删,改,增),关闭为一体的Java类

10 篇文章 0 订阅
4 篇文章 0 订阅

package com.gxichenxuyuan.cn.datebase;
import java.sql.*;
/**

  • 数据库访问操作管理类
  • @author 演示

/
public class DbUtil {
private static final String driverClass=“com.mysql.jdbc.Driver”;
//power为数据库名
private static final String url=“jdbc:mysql://127.0.0.1:3306/power?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true”;
private static final String user=“root”; //数据库用户
private static final String password=“123456”; //数据库密码
/
*
* 获取数据库连接
* @return
/
public static Connection getConn(){
Connection conn =null;
try{
Class.forName(driverClass);
conn =DriverManager.getConnection(url, user, password);
}catch (Exception e) {
e.printStackTrace();
}
return conn;
}
/
*
*
* @param sql
* @throws SQLException
/
public void executeUpdate(String sql)throws SQLException{
Connection conn=null;
Statement stmt=null;
try{
conn=getConn();
stmt=conn.createStatement();
stmt.executeUpdate(sql);
}catch (SQLException e) {
throw new SQLException(“执行SQL更新失败:”+e.getMessage(),e);
}finally{
close(stmt, conn);
}
}
/
*
*
* @param sql
* @throws SQLException
/
public ResultSet executeQuery(Statement stmt,String sql)throws SQLException{
ResultSet rs=null;
try{
rs=stmt.executeQuery(sql);
return rs;
}catch (SQLException e) {
throw new SQLException(“执行SQL查询失败”+e.getMessage(),e);
}
}
public static void close(ResultSet rs,Statement stmt,Connection conn)throws SQLException{
try{
if(rs!=null){
rs.close();
}
if(stmt!=null){
stmt.close();
}
if(conn!=null){
conn.close();
}
}catch (SQLException e) {
throw new SQLException(“关闭数据库连接资源失败!”+e.getMessage(),e);
}
}
public static void close(Statement stmt,Connection conn)throws SQLException{
close(null, stmt, conn);
}
/
*
* 关闭连接
* @param conn
* @throws SQLException
/
public static void close(Connection conn)throws SQLException{
close(null, null, conn);
}
/
*
* 关闭Statement
* @param conn
* @throws SQLException
*/
public static void close(Statement stmt)throws SQLException{
close(null, stmt, null);
}

}

注:以上查找与更新数据库关键在于参数sql语句的调用,在调用时还要对调用的那段语句进行异常处理才行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值