Java 在执行多个SQL查询时,是否应尝试使用相同的连接?

Java 在执行多个SQL查询时,是否应尝试使用相同的连接?,java,mysql,database-connection,Java,Mysql,Database Connection,因此,有时在Java应用程序中,我需要用相同的方法向MySQL数据库发送多个查询 我正在应用程序中使用连接池: private static final BasicDataSource dataSource = new BasicDataSource(); static { dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://---

因此,有时在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("----");
    }
我的数据库类中有一个方法:

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()
,或者即使我正在这样做,也可以从池中获取一个新的
连接

init() {

    Employee employee1= DataBase.getEmployee(11);
    Employee employee2 = DataBase.getEmployee(12);
}
我可以实现这两行代码将使用相同的
连接
,但这是明智的还是不必要的


//旁注:员工id从未从用户输入,因此不可能在那里进行SQL注入

这意味着在现有连接池的基础上运行自己的连接池。要使这两个层干净地相互作用并不容易

但是,通过将打开的连接传递到getEmployee()方法,您可能会获得性能改进,这样您就可以在外部获取连接,将其用于多个连续调用,然后关闭它。但我不知道它会带来多大的性能差异,而且与当前的体系结构相比,它肯定会使您的代码不那么优雅