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语句的调用,在调用时还要对调用的那段语句进行异常处理才行。