gpt4 book ai didi

java - JDBCPreparedStatements 与对象 - 在哪里放置初始化

转载 作者:行者123 更新时间:2023-12-02 08:10:24 25 4
gpt4 key购买 nike

当我想将PreparedStatement初始化用于给定类的所有实例时,放置PreparedStatement初始化的最佳位置是什么?

到目前为止,我的解决方案是创建用于打开和关闭的静态方法,但我认为它不是正确的选择:

class Person {
protected static PreparedStatement stmt1;
protected static PreparedStatement stmt2;

protected static void initStatements(Connection conn) {
stmt1 = conn.PrepareStatement("select job_id from persons where person_id=:person_id");
stmt2 = conn.PrepareStatement("update persons set job_id=:job_id where person_id=:person_id");
}

protected static void closeStatements() {
stmt1.close();
stmt2.close();
}
public void increaseSalary() {
stmt1.execute(); // just a example
stmt2.execute();
}
}

void main {
// create prepared statements
Person.initStatements(conn);

// for each person, increase do some action which require sql connection
for (Person p : getAllPersons()) {
p.increaseSalary();
}

// close statements
Person.closeStatements();
}

没有其他方法可以在类的多个实例中使用PreparedStatements吗?

最佳答案

person 会是你的领域逻辑类吗?那么我建议不要将数据访问方法和PreparedStatements 放在那里,而是放在单独的数据访问对象中。

DAO 方法是否会在 Web 应用程序中异步调用?然后我建议根本不要在这些调用之间重用PreparedStatements 或连接。对于连接,我将使用连接池。更多关于重用PreparedStatements的信息: Reusing a PreparedStatement multiple times

关于java - JDBCPreparedStatements 与对象 - 在哪里放置初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7529037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com