Каков наилучший способ поместить результат for
Statement в таблицу 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);
}
}
}
Я рекомендую вам использовать подготовленные заявления:
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()
для большинства типов данных SQL (и 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
}
Рекомендации:
Вы можете попробовать это.
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);
}
}
}
PreparedStatement
при отправке параметров на ваши запросы при использовании JDBC.