初级优化
1. JdbcUtil工具类优化
a. 准备 db.properties
driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/java2021?useSSL=false
username=root
password=123456
b. 使用Properties读取配置文件操作
private static String jdbcUrl;
private static String username;
private static String password;
static {
try {
Properties properties = new Properties();
properties.load(new FileInputStream("./src/db.properties"));
jdbcUrl = properties.getProperty("jdbcUrl");
username = properties.getProperty("username");
password = properties.getProperty("password");
Class.forName(properties.getProperty("driverClass"));
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
c. 对象获取和资源关闭总结
package util;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
public class JdbcUtil {
private static String jdbcUrl;
private static String username;
private static String password;
static {
try {
Properties properties = new Properties();
properties.load(new FileInputStream("./src/db.properties"));
jdbcUrl = properties.getProperty("jdbcUrl");
username = properties.getProperty("username");
password = properties.getProperty("password");
Class.forName(properties.getProperty("driverClass"));
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection connection = null;
try {
connection = DriverManager.getConnection(jdbcUrl, username, password);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public static void close(Connection conn) {
close(conn, null, null);
}
public static void close(Connection conn, Statement st) {
close(conn, st, null);
}
public static void close(Connection conn, Statement st, ResultSet rs) {
try {
close(rs, st, conn);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void close(AutoCloseable... res) throws Exception {
for (AutoCloseable re : res) {
if (re != null) {
re.close();
}
}
}
}
2. 整合更新和查询方法
方法封装
package util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class BaseDao {
public int update(String sql, Object... parameters) {
if (null == sql) {
throw new IllegalArgumentException("SQL is null");
}
int affectedRows = 0;
PreparedStatement statement = null;
Connection connection = JdbcUtil.getConnection();
try {
statement = connection.prepareStatement(sql);
int parameterCount = statement.getParameterMetaData().getParameterCount();
if (!(0 == parameterCount || null == parameters || parameterCount != parameters.length)) {
for (int i = 0; i < parameterCount; i++) {
statement.setObject(i + 1, parameters[i]);
}
}
affectedRows = statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.close(connection, statement);
}
return affectedRows;
}
}