我正在尝试将数组变量插入表中。代码如下所示
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
class PostgreSQLJDBC {
public static void main(String args[]) {
Connection c = null;
Statement stmt = null;
Statement stmt1 = null;
int id[] = new int[3];
int no = 1;
id[0] = 2;
id[1] = 14;
id[2] = 4;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager
.getConnection("jdbc:postgresql://localhost:5432/ass2",
"postgres", "post");
c.setAutoCommit(true);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql1 = "INSERT INTO COMPANY (NO,ID) "
+ "VALUES (7, id);";
stmt1 = c.createStatement();
stmt1.executeUpdate(sql1);
stmt1.close();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Operation done successfully");
}
}
此代码编译 but gives an PSQLexception.
有人可以帮忙解决这个问题吗
最佳答案
尝试使用Prepared Statement所以你可以使用 setArray像这样:
但是首先你不能设置 int[]
你必须把它转换成数组,所以你可以使用:
Integer[] id = {2, 14, 4};
Array array = connection.createArrayOf("INTEGER", id);
然后创建准备好的语句并设置数组:
String sql = "INSERT INTO COMPANY (NO, ID) VALUES (?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(sql);) {
pstmt.setInt(1, 7); // Set NO
pstmt.setArray(2, array); // Set ID
pstmt.executeUpdate(); // Execute the query
}
注意:请避免在 PostgreSQL
中的表名和列名中使用大写字母!这可能会产生一些问题,而您的查询应该如下所示:
INSERT INTO company (no, id) VALUES (?, ?)
关于java - JDBC - 将数组变量插入到 PostgreSQL 表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48643892/