突然心血来潮,想找一个BaseDao工具类,找半天找不到,就自己写了一个,方便后续使用。
package com.zzw.wxmall.dao;
import java.sql.*;
/**
* @author zzw
* @description TODO
* @date 2022-11-11 15:18
*/
public class BaseDao {
private final String DRIVER="com.mysql.cj.jdbc.Driver"; // mysql
// private final String DRIVER="com.microsoft.sqlserver.jdbc.SQLServerDriver"; // SqlServer
private final String URL= "jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai"; // mysql
// private final String URL= "jdbc:sqlserver://localhost:1433;databaseName=数据库名"; // SqlServer
private final String USERNAME = "root"; // 用户名
private final String PWD = "root"; // 密码
private Connection connection;
private PreparedStatement ps;
protected ResultSet rs;
/**
* 打开连接
*/
public void getConnection(){
try {
Class.forName(DRIVER);
// 2在网络中查找数据库,创建连接对象
connection = DriverManager.getConnection(
URL, USERNAME,PWD);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//return connection;
}
/**
* 关闭连接
*/
public void closeAll(){
try {
// 释放资源(后打开的先关闭,先打开的后关闭)
if (rs != null)
rs.close();
if (ps != null)
ps.close();
if (connection != null)
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 查询
* @param sql
* @param params
*/
public void executeQuery(String sql , Object... params){
try {
getConnection();
ps = connection.prepareStatement(sql);
if(params!= null){
for (int i = 0; i < params.length; i++) {
ps.setObject(i+1, params[i]);
}
}
rs = ps.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 增、删、改
* @param sql
* @param params
* @return
*/
public int executeUpdate(String sql , Object... params){
int result = -1;
try {
getConnection();
ps = connection.prepareStatement(sql);
if(params!= null){
for (int i = 0; i < params.length; i++) {
ps.setObject(i+1, params[i]);
}
}
result= ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
this.closeAll();
}
return result;
}
}
版权声明:本文为ITKidKid原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。