Java数据事务性能

时间:2015-12-02 23:56:23

标签: java jdbc database-connection database-performance

我知道如何使用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;
    } 
}

当我必须关闭连接或关闭自动提交时?

我可以做些什么来改善我的应用数据交易效果?如何进行数据交易的正确方法?或者更好地做任何提示?

1 个答案:

答案 0 :(得分:1)

  

当我必须关闭我的连接时?

如果您在Java EE环境中运行(即在应用服务器上),那么您可以根据需要获取和关闭连接,因为除非您明确禁用连接池,否则大多数Java EE环境将为您汇集JDBC连接。

如果您在Java SE环境中运行,这取决于您获得连接的方式。对于这个例子,看起来你正在做一堆静态导入(which is bad practice by the way),但是你可以告诉你我正在使用DriverManager来获取你的连接。如果这是真的并且您正在使用DriverManager,那么获取连接非常昂贵!特别是一旦开始使用远程数据库。您将尝试缓存您的连接。或者,您可以使用javax.sql.ConnectionPoolDataSource并使用getPooledConnection(),这将为获取/关闭方案提供更高的性能,并为您处理连接缓存。

  

什么时候应该打开/关闭自动提交?

自动提交开启或关闭并不是一件大事。我总是希望保持自动提交,因为通过将提交责任留给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();
}