用户管理系统工具类(连接,查询,增删改)(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;
}