Java 数据交易性能

Java data transaction performance

我知道如何用JDBC开通数据交易。但我想我 can/must 做了一些事情来提高数据交易性能。例如:

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(),这将在 get/close 场景中具有更高的性能,并为您处理连接缓存。

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();
}