在看視頻學習過程中,看到有老師自己封裝的數據庫工具類,感覺用起來很方便;自己也跟着寫了一個,以後再使用JDBC時可直接使用。
import java.sql.*;
/**
* JDBC的工具類
*/
public class DBUtil {
private static Connection conn = null;
private static PreparedStatement pstmt = null;
private static ResultSet rs = null;
private DBUtil(){
}
/**
* 創建一個連接
*/
public static Connection getConnection() {
String url = "jdbc:mysql:// localhost:3306/test?serverTimezone=GMT%2B8";
try {
//加載驅動
Class.forName("com.mysql.cj.jdbc.Driver");
//建立連接
conn = DriverManager.getConnection(url, "root", "123456");
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
/**
* 關閉數據庫資源
*/
public static void closeAll() {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (pstmt != null) {
pstmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 執行insert、update、delelte 三個DML操作
* 傳入參數sql語句,以及sql語句中佔位符對應的數據
*/
public static int executeUpdate(String sql, Object[] prams){
conn = getConnection();
int n = 0;
try {
pstmt = conn.prepareStatement(sql);
for (int i=0;i<prams.length;i++){
pstmt.setObject(i+1,prams[i]);
}
n=pstmt.executeUpdate();
}catch (SQLException e){
e.printStackTrace();
}
return n;
}
/**
* 執行查詢所返回的Resultset對象
*/
public static ResultSet executeQuery(String sql, Object[] prams){
conn = getConnection();
try {
pstmt = conn.prepareStatement(sql);
for (int i=0;i<prams.length;i++){
pstmt.setObject(i+1,prams[i]);
}
rs = pstmt.executeQuery();
}catch (Exception e){
e.printStackTrace();
}
return rs;
}
}
增加數據操作:
public int addUser(String uname, String pwd) {
String sql = "insert into t_user values(default,?,?)";
Object[] prams = {uname, pwd};
int ok = DBUtil.executeUpdate(sql, prams);
DBUtil.closeAll();
return ok;
}
刪除數據操作:
String sql = "delete from t_user where uid=?";
Object[] prams = {4};
int ok = DBUtil.executeUpdate(sql, prams);
DBUtil.closeAll();
更新數據操作:
String sql = "update t_user set pwd=? where uname=?";
String uname = "lisi";
String pwd = "789";
Object[] prams = {pwd, uname};
int ok = DBUtil.executeUpdate(sql, prams);
DBUtil.closeAll();
查詢數據操作:
public User login(String uname, String pwd) {
String sql = "select * from t_user where uname=? and pwd=?";
Object[] prams = {uname, pwd};
ResultSet rs = DBUtil.executeQuery(sql, prams);
User user = null;
try {
while (rs.next()) {
int uid = rs.getInt("uid");
String name = rs.getString("uname");
String pwd2 = rs.getString("pwd");
user = new User(uid, name, pwd2);
}
} catch (SQLException e) {
e.printStackTrace();
}
DBUtil.closeAll();
return user;
}