在Java中,PreparedStatement如何适用于以下查询

时间:2010-09-14 01:54:07

标签: java performance mysql prepared-statement

我有一个类似下面的查询,并想知道通过批处理PreparedStatement生成什么样的SQL。

INSERT INTO table1 (id, version, data)
  VALUES (?, ?, ?)
  ON DUPLICATE KEY UPDATE 
    table1.data = IF(table1.version > table2.version, table1.data, table2.data),
    table1.version = IF(table1.version > table2.version, table1.version, table2.version)

问题是,它是否会将此解析为批处理中每行的整个sql字符串的副本,或者它是否会执行以下操作:

INSERT INTO table1 (id, version, data)
  VALUES (a1, b1, c1), (a2, b2, c2), (a3, b3, c3), ...
  ON DUPLICATE KEY UPDATE 
    table1.data = IF(table1.version > table2.version, table1.data, table2.data),
    table1.version = IF(table1.version > table2.version, table1.version, table2.version)

如果没有,那么性能含义是什么?如何编写它以便我可以使用PreparedStatement批处理这些INSERT..UPDATE语句而不会导致性能损失?

1 个答案:

答案 0 :(得分:2)

准备好的语句只是将您放入的位置值插入到重复语句中,然后每次都不需要解析。因此,您的第二种形式只需要N * 3参数,并且不会为您提供准备好的语句的任何速度提升。对于重复语句,您要使用addTobatch。基本上你准备语句,(例如“更新......??”然后一次添加3个参数,并一次执行批处理。

我曾经使用类似这样的东西来包装它的混乱。所以你只需做类似

的事情
  SQLBatchHandler h = new SQLBatchHandler(conn, "UPDATE ... WHERE ? ? ? ... ");
  h.addToBatch(x, y,z);
  h.addToBatch(x2,y2,z2);
  ...
  h.flush();



public class SQLBatchHandler {
    public static int           MAX_BATCH_SIZE  = 500;
    public String           query;
    private Connection      conn;
    private PreparedStatement   ps;
    private int             batch_ct;

    public SQLBatchHandler(Connection c, String query) throws SQLException
        {
        conn = c;
        this.query = query;
        ps = conn.prepareStatement(query);
    }

    /**
     * add this row to the batch and handle the commit if the batch size
     * exceeds {@link #MAX_BATCH_SIZE}
     * 
     * @param values row values
     * @throws SQLException
     */
    public void addToBatch(Object ... values) throws SQLException
    {
        int i = 0;
        for (Object value: values)
        {
            ps.setObject((++i), value);
        }
        add();
    }

    private void add() throws SQLException
    {
        ps.addBatch();
        if ((++batch_ct) > MAX_BATCH_SIZE)
        {
            ps.executeBatch();
            batch_ct = 0;
        }
    }

    /**
     * Commit any remaining objects and close.
     * 
     * @throws SQLException On statement close error.
     */
    public void flush() throws SQLException
    {
        if (batch_ct == 0) { return; }
        try
        {
            ps.executeBatch();
        }
        catch (SQLException e)
        {
            throw e;
        }
        finally
        {
            if (ps != null)
            {
                ps.close();
            }
        }
    }
}