何时创建/初始化预准备语句

时间:2014-08-27 16:39:46

标签: java jdbc javadb

我有以下具有2种方法的Query类,insert()方法经常使用,而deleteRecord()则不常用。

public class Query1 {

private final static String INSERT = "insert into info values (?, current_timestamp)";
private final static String DELETE_RECORD = "delete from info where stamp = ?";

private static final Connection con = DatabaseConnection.getInstance();

//This method is used frequently
public static void insert(List<String> numList) throws SQLException {
    try (PreparedStatement st_insert = con.prepareStatement(INSERT)) {
        for (int i = 0; i < numList.size(); i++) {
            st_insert.setString(1, numList.get(i));
            st_insert.addBatch();
        }
        st_insert.executeBatch();
    }
}

// This method is NOT used frequently
public static void deleteRecord(Timestamp stamp) throws SQLException {
    try (PreparedStatement st = con.prepareStatement(DELETE_RECORD)) {
        st.setTimestamp(1, stamp);
        st.execute();
    }
}

我将Query1类转换为下面,其中insert()方法使用的PreparedStatement在静态块中初始化,因为它经常被使用。

public class Query2 {
private final static String INSERT = "insert into info values (?, current_timestamp)";
private final static String DELETE_RECORD = "delete from info where stamp = ?";

private static final Connection con = DatabaseConnection.getInstance();

// Frequently used statements
private static PreparedStatement st_insert;
static {
    try {
        st_insert = con.prepareStatement(INSERT);
    } catch (SQLException ex) {            
    }
}

//This method is used frequently
public static void insert(List<String> numList) throws SQLException {        
    for (int i = 0; i < numList.size(); i++) {
        st_insert.setString(1, numList.get(i));            
        st_insert.addBatch();
    }
    st_insert.executeBatch();
}

// This method is NOT used frequently
public static void deleteRecord(Timestamp stamp) throws SQLException {
    try (PreparedStatement st = con.prepareStatement(DELETE_RECORD)) {
        st.setTimestamp(1, stamp);
        st.execute();
    }
}

考虑到使用预准备语句,这是否会优化代码,或者这不是一个好习惯吗?如果不是怎么做的话? (我是JDBC的初学者,并没有遇到过像这样的代码示例。)

任何建议都将不胜感激。

1 个答案:

答案 0 :(得分:1)

你的推理是正确的。经常执行的查询可以从使用PreparedStatement中受益。正确的权衡取决于DB之间的差异。您使用javadb进行了标记,如果这是您使用的,那么PreparedStatements永远不会慢,因为常规语句会经历相同的编译过程。

那就是说,我同意那些建议不要在静态区块中准备声明的人。 我通常尝试在构造函数或init方法中准备语句,以便我可以在经常调用的方法中重用ps。

另请注意,即使是ps也可以重新编译并在背后&34;因为可能影响查询必须/应该如何执行的更改(添加索引,更改统计信息,更改权限等)。