用戶管理系統工具類(連接,查詢,增刪改)(servlet+jdbc)
工具類具體實現了哪些功能:
- 連接功能,先在靜態代碼塊兒加載資源(Connection)這裏Class.forName有一個裝載類對象的作用,JDBC規範要求Driver類在使用前必須向DriverManger註冊自己。註冊過程在Driver類的靜態類已經實現。也就是說只要類被加載,就完成了向驅動管理器的註冊。
- 查詢功能,(executeQuery)由於在執行查詢方法時好多代碼都是相同的,所以我們把他包裝成一個類
- 增刪改功能,(executeUpdate)與查詢功能類似
package com.lxs.util;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class util {
private static String driver;
private static String url;
private static String user;
private static String password;
static {
Properties properties = new Properties();
InputStream is = util.class.getClassLoader().getResourceAsStream("db.properties");
try {
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
}
driver = properties.getProperty("driver");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
}
//獲取連接
public static Connection getConnection() {
Connection connection = null;
try {
Class.forName(driver);
connection = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
//查詢類方法
public static ResultSet query(PreparedStatement preparedStatement, Connection connection, ResultSet resultSet, String sql, Object[] params) {
try {
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
preparedStatement.setObject(i + 1, params[i]);
}
resultSet = preparedStatement.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return resultSet;
}
//增刪改方法
public static int update(PreparedStatement preparedStatement, Connection connection, ResultSet resultSet, String sql, Object[] params) throws SQLException {
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
preparedStatement.setObject(i + 1, params[i]);
}
int update = preparedStatement.executeUpdate();
return update;
}
//關閉資源
public static boolean closeResource(PreparedStatement preparedStatement, Connection connection, ResultSet resultSet){
boolean flag = true;
if(resultSet != null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
flag = false;
}
}
if(preparedStatement != null){
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
flag = false;
}
}
if(connection != null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
flag = false;
}
}
return flag;
}