public class BaseDao {
//定义驱动
private String driver="com.mysql.jdbc.Driver";
//定义数据库地址
private String url="jdbc:mysql://localhost:3306/kj12?characterEncoding=UTF8&serverTimezone=UTC";
//定义用户名
private String userName="root";
//定义密码
private String password="root";
//创建Connection
private Connection conn=null;
//创建PreparedStatement
private PreparedStatement pstm=null;
/**
* 获取连接
* @return
*/
public Connection getConn(){
try {
//加载驱动
Class.forName(driver);
//连接数据库
return conn= DriverManager.getConnection(url,userName,password);
} catch (ClassNotFoundException e) {
System.out.println("连接驱动失败!");
} catch (SQLException throwables) {
System.out.println("连接数据库失败!");
}
return null;
}
/**
* 关闭资源
* @param res
* @param pstm
* @param conn
*/
public void closeAll(ResultSet res, PreparedStatement pstm,Connection conn){
if (res!=null){
try {
res.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (pstm!=null){
try {
pstm.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn!=null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
/**
* 增通用删改方法
* @param sql
* @param objects
* @return
*/
public int executeUpdate(String sql,Object... objects){
//获取连接
conn=getConn();
int res=0;
try {
//接收sql语句
pstm=conn.prepareStatement(sql);
//将sql语句中的?填充指定参数
for (int i = 0; i < objects.length; i++) {
pstm.setObject(i+1,objects[i]);
}
//执行增删改sql
res=pstm.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
//关闭资源
closeAll(null,pstm,conn);
}
return res;
}
/**
* 通用查询方法
* @param sql
* @param objects
* @return
*/
public ResultSet executeQuery(String sql,Object... objects){
//获取连接
conn=getConn();
ResultSet res=null;
try {
//接收sql语句
pstm=conn.prepareStatement(sql);
//将sql语句中的?填充指定参数
for (int i = 0; i < objects.length; i++) {
pstm.setObject(i+1,objects[i]);
}
//执行查询sql
res=pstm.executeQuery();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
//将结果集返回
return res;
}
}
Java mysql连接
最新推荐文章于 2024-09-06 10:46:37 发布