我知道如何使用 JDBC 开启数据事务。但我认为我可以/必须做一些事情来提高数据事务性能。例如:
public class F_Koneksi {
private static final String JDBC_DRIVER;
private static final String DB_URL;
private static final String USER;
private static final String PASS;
static {
JDBC_DRIVER = "org.postgresql.Driver";
DB_URL = "jdbc:postgresql://localhost:5432/MyDatabase";
USER = "Username";
PASS = "Password";
}
private final Connection con;
private ResultSet rs;
private Statement stmt;
public F_Koneksi() {
Connection connect;
try {
Properties props = new Properties();
props.setProperty("user", USER);
props.setProperty("password",PASS);
props.setProperty("sslfactory", "org.postgresql.ssl.NonValidatingFactory");
props.setProperty("ssl", "true");
forName(JDBC_DRIVER);
connect = getConnection(DB_URL, props);
} catch (SQLException|ClassNotFoundException se) {
connect = null;
}
con = connect;
}
public boolean Update(String Query) {
try {
Query = Query.replaceAll("`", "\"");
System.out.println(Query);
Statement stmt = con.createStatement();
stmt.executeUpdate(Query);
return true;
} catch (SQLException ex) {
ex.printStackTrace();
return false;
}
}
以及何时我必须关闭连接或关闭自动提交?
<小时/>我可以采取哪些措施来提高我的应用数据事务性能?怎样才是正确的数据交易方式呢?或者有什么技巧可以做得更好吗?
最佳答案
When i must close my connection?
如果您在 Java EE 环境中(即在应用程序服务器上)运行,那么您可以根据需要获取和关闭连接,因为大多数 Java EE 环境将为您池化 JDBC 连接,除非您明确禁用连接池。
如果您在 Java SE 环境中运行,这取决于您获取连接的方式。对于这个示例,看起来您正在执行一堆静态导入( which is bad practice by the way ),但我可以告诉您正在使用 DriverManager 来获取连接。如果这是真的并且您正在使用 DriverManager,那么获取连接的成本非常昂贵!尤其是当您开始使用远程数据库时。您将需要尝试缓存您的连接。或者,您可以使用 javax.sql.ConnectionPoolDataSource 并使用 getPooledConnection() ,这将为获取/关闭场景提供更高的性能,并为您处理连接缓存.
When should I turn auto-commit on/off?
打开或关闭自动提交并不是什么大问题。我总是喜欢启用自动提交,因为将提交责任留给 JDBC 驱动程序可以减少出错的可能性。
对语句进行批处理会对您的性能有很大帮助。
例如:
try(Statement statement = conn.createStatement()){
statement.addBatch("update people set firstname='Alice' where id=1");
statement.addBatch("update people set firstname='Bob' where id=2");
statement.addBatch("update people set firstname='Chuck' where id=3");
statement.executeBatch();
}
关于Java数据事务性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34055413/