package com.goods.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
jdbc的封装
sql语句不同,参数不同(列表,个数,顺序..等),
jdbc的增删改三步:
1. DBUtil db=new DBUtil();
2. db.insert(sql,参数); 3. db.close();
2. db.delete(sql,参数); 3. db.close();
2. db.update(sql,参数); 3. db.close();
查: 2. ResultSet rs=db.query(sql,参数);
3. 创建对象的集合,对象.set(rs.get(字段)),集合.add(对象), db.close(rs);
*/
public class DBUtil {
// 防中文乱码:?useUnicode=true&characterEncoding=UTF-8
public static final String URL = "jdbc:mysql://localhost:3306/goods?useUnicode=true&characterEncoding=UTF-8";
public static final String USER = "root";
public static final String PASSWORD = "123";
private Connection conn = null;
private PreparedStatement stat = null;
static {
try {
// 数据库驱动
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("缺少数据库驱动包");
}
}
// 获取连接方法
public Connection getConnection() {
// 创建连接
try {
if (conn == null || conn.isClosed()) {
conn = DriverManager.getConnection(URL, USER, PASSWORD);
}
return conn;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
// 查
public ResultSet query(String sql, Object... params) {
try {
// 创建连接的方法,调用公用的方法
getConnection();
// 预编译语句
stat = conn.prepareStatement(sql);
// 设置参数
putParams(stat, params);
// 执行
ResultSet rs = stat.executeQuery();
return rs;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
// 改
public int update(String sql, Object... params) {
return executeUpdate(sql, params);
}
// 删
public int delete(String sql, Object... params) {
return executeUpdate(sql, params);
}
// 增
public int insert(String sql, Object... params) {
return executeUpdate(sql, params);
}
// ...表示参数可传可不传, params数组
public int executeUpdate(String sql, Object... params) {
try {
// 创建连接的方法,调用公用的方法
getConnection();
// 预编译语句
stat = conn.prepareStatement(sql);
// 设置参数
putParams(stat, params);
// 执行事务
int rlt = stat.executeUpdate();
return rlt;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
// 设置参数方法
private void putParams(PreparedStatement stat, Object... params) throws SQLException {
if (params != null) {
for (int i = 0; i < params.length; i++) {
stat.setObject(i + 1, params[i]);
}
}
}
// 关闭方法
public void close() {
try {
if (stat != null) {
stat.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void close(ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
jdbc的封装
最新推荐文章于 2023-09-28 21:02:25 发布