将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);
}
}
}
答案 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
}
准备好的陈述有一些优点:
setXXX()
个方法(如果需要,可以使用setNull()
方法)。批量示例:
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);
}
}
}