我建議你使用準備好的語句:
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
}
預處理語句有一定的優勢:
- 您可以編寫SQL指令只有一次,並使用了很多次。您只需輸入佔位符的索引(從1開始)並分配適當的值。對於大多數SQL數據類型,有
setXXX()
方法(如果需要的話可以使用setNull()
方法)。
- 預處理語句有助於防止SQL injection attacs((關於什麼是SQL注入攻擊的風險,一個有趣的例子,檢查xkcd: Exploits of a Mom)。
- 如果你有大量的指令,你可以在一個批次中執行它們。
批次例如:
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
}
個參考文獻:
您是否在創建數據庫中的表?它的結構是什麼(顯示CREATE TABLE語句)? –
CREATE TABLE語句不在此代碼中,但表已創建...我也測試了連接並執行了一個簡單的INSERT,如「INSERT INTO multiplication VALUES(3,6,9,12,15)」工作得很好。 – Lopestt
爲了適應規則並幫助其他用戶,重新編寫了問題。 – Lopestt