2014-07-01 19 views
1

for聲明的結果放入PostgreSQL表中的最佳方式是什麼?如何將for語句的結果放入表中?

例子:

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); 
     } 
    } 
} 
+0

您是否在創建數據庫中的表?它的結構是什麼(顯示CREATE TABLE語句)? –

+0

CREATE TABLE語句不在此代碼中,但表已創建...我也測試了連接並執行了一個簡單的INSERT,如「INSERT INTO multiplication VALUES(3,6,9,12,15)」工作得很好。 – Lopestt

+0

爲了適應規則並幫助其他用戶,重新編寫了問題。 – Lopestt

回答

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. 如果你有大量的指令,你可以在一個批次中執行它們。

批次例如:

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

如果大小^ 2產生大量的操作,例如大小= 100,這將生成10K插入,您可能想要批量插入這些。 –

+0

@LuiggiMendoza筆記採取...更新後包括此替代 – Barranka

+0

感謝您的幫助!我的表有五列,我會指定它們,以便它可以正確插入值。 – Lopestt

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); 
     } 
    } 
} 
+0

***警告!***您的代碼容易受到[SQL注入攻擊](http://en.wikipedia.org/wiki/SQL_injection) – Barranka

+1

當您向查詢發送參數時,您可能會嘗試使用'PreparedStatement'使用JDBC。 –

+0

(有關SQL注入攻擊風險的有趣示例,請查看[xkcd:Exploits of a Mom](http://xkcd.com/327/)) – Barranka