在执行多个 SQL 查询时,我应该尝试使用相同的连接吗?
When doing multiple SQL queries should I try to use same connection?
所以有时在我的 Java 应用程序中,我需要用相同的方法向我的 MySQL 数据库发送多个查询。
我在我的应用程序中使用连接池:
private static final BasicDataSource dataSource = new BasicDataSource();
static {
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://--------:---/agenda?useSSL=true");
dataSource.setUsername("----");
dataSource.setPassword("----");
}
我的数据库中有一个方法class:
public static Employee getEmployee(int id) {
Employee employee = null;
try { String query = "SELECT * FROM entity WHERE entityId = " + id + " LIMIT 0, 1;";
Connection con = dataSource.getConnection();
java.sql.Statement indexStmt = con.createStatement();
ResultSet indexRs = indexStmt.executeQuery(query);
while (indexRs.next()) {
employee = new Employee(indexRs.getInt(1),
indexRs.getString(3), indexRs.getString(4),
indexRs.getString(5), indexRs.getString(6));
}
indexStmt.close();
indexRs.close();
con.close();
} catch (SQLException e) {e.printStackTrace();}
return employee;
}
我应该花时间尝试使用相同的 Connection con = DataBase.getSource()
还是从池中获取一个新的 connection
是否可以,即使我正在做这样的事情?
init() {
Employee employee1= DataBase.getEmployee(11);
Employee employee2 = DataBase.getEmployee(12);
}
我可以实现这两行代码使用相同的东西 connection
但这样做是明智的还是不必要的?
//旁注,员工 ID 永远不会从用户输入,因此 SQL 注入是不可能的。
这意味着 运行 在现有连接池之上建立您自己的连接池。要让这两层干净利落地交互并不容易。
但是您可能会通过将打开的连接传递到您的 getEmployee() 方法来提高性能,这样您就可以在外部获取连接,将其用于多个连续调用,然后关闭它。但我不知道它带来了多少性能差异,与当前架构相比,它肯定会使您的代码不那么优雅。
所以有时在我的 Java 应用程序中,我需要用相同的方法向我的 MySQL 数据库发送多个查询。
我在我的应用程序中使用连接池:
private static final BasicDataSource dataSource = new BasicDataSource();
static {
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://--------:---/agenda?useSSL=true");
dataSource.setUsername("----");
dataSource.setPassword("----");
}
我的数据库中有一个方法class:
public static Employee getEmployee(int id) {
Employee employee = null;
try { String query = "SELECT * FROM entity WHERE entityId = " + id + " LIMIT 0, 1;";
Connection con = dataSource.getConnection();
java.sql.Statement indexStmt = con.createStatement();
ResultSet indexRs = indexStmt.executeQuery(query);
while (indexRs.next()) {
employee = new Employee(indexRs.getInt(1),
indexRs.getString(3), indexRs.getString(4),
indexRs.getString(5), indexRs.getString(6));
}
indexStmt.close();
indexRs.close();
con.close();
} catch (SQLException e) {e.printStackTrace();}
return employee;
}
我应该花时间尝试使用相同的 Connection con = DataBase.getSource()
还是从池中获取一个新的 connection
是否可以,即使我正在做这样的事情?
init() {
Employee employee1= DataBase.getEmployee(11);
Employee employee2 = DataBase.getEmployee(12);
}
我可以实现这两行代码使用相同的东西 connection
但这样做是明智的还是不必要的?
//旁注,员工 ID 永远不会从用户输入,因此 SQL 注入是不可能的。
这意味着 运行 在现有连接池之上建立您自己的连接池。要让这两层干净利落地交互并不容易。
但是您可能会通过将打开的连接传递到您的 getEmployee() 方法来提高性能,这样您就可以在外部获取连接,将其用于多个连续调用,然后关闭它。但我不知道它带来了多少性能差异,与当前架构相比,它肯定会使您的代码不那么优雅。