如何将for语句的结果放入表中?

时间:2014-07-01 23:06:01

标签: java postgresql for-loop

for语句的结果放入PostgreSQL表的最佳方法是什么?

示例:

int size = 5;
try {
    for (int i = 1; i <= size; i++) {
        for (int j = 1; j <= size; j++) {
            ??? x = (i * j); 

            String sql = "INSERT INTO multiplication" +
                         "VALUES (???)";
            ResultSet rs = stmt.executeQuery(sql);
        }
    }
}

2 个答案:

答案 0 :(得分:3)

我建议你使用准备好的陈述:

int size = 5;
String strSQL = "insert into multiplication values (?)"; 
/* 
 * I am assuming your table has only one column.
 * If it has more columns, you need to specify the column where you want 
 * to insert the value:
 *     "insert into multiplication (col1) values (?)"
 *
 * The question mark is a place-holder for the value you are about to insert.
 *
 * I am also assuming that you have a Connection object named "conn".
 */
try(PreparedStatement ps = conn.prepareStatement(strSQL)) {
    for(int i = 1; i <= size; i++) {
        for(int j = 1; j <= size; j++) {
            /*
             * You are multiplying integers, so the result is also an integer
             */
            int x = i * j;
            /*
             * Assign the value to the prepared statement
             */
            ps.setInt(1, x);
            ps.execute(); // The statement is executed HERE
        }
    }
} catch(SQLException e) {
    // Exception handling code
}

准备好的陈述有一些优点:

  1. 您只能编写一次SQL指令,并多次使用它。您只需输入占位符的索引(从1开始)并指定适当的值。大多数SQL数据类型都有setXXX()个方法(如果需要,可以使用setNull()方法)。
  2. 预备语句有助于防止SQL injection attacs((有关SQL注入攻击的风险的一个有趣例子,请检查xkcd: Exploits of a Mom)。
  3. 如果您有大量说明,则可以批量执行。
  4. 批量示例:

    int size = 5;
    String strSQL = "insert into multiplication values (?)"; 
    try(PreparedStatement ps = conn.prepareStatement(strSQL)) {
         for(int i = 1; i <= size; i++) {
             for(int j = 1; j <= size; j++) {
                 int x = i * j;
                 ps.setInt(1, x);
                 ps.addBatch(); // The statement is added to the batch (but not executed yet)
             }
         }
         ps.executeBatch(); // All the instructions in the batch are executed HERE
     } catch(SQLException e) {
         // Exception handling code
     }
    

    <强>参考文献:

答案 1 :(得分:0)

你可以试试这个。

int size = 5; 
try {
    for (int i = 1; i <= size; i++) {
        for (int j = 1; j <= size; j++) {
            String x = String.valueOf(i * j); 

            String sql = "INSERT INTO multiplication" +
                     "VALUES (" + x + ")";
            ResultSet rs = stmt.executeQuery(sql);
        }
    }
}