我正在编写一个生成随机数据并用它填充 PostgreSQL 表的程序。您会发现我尝试执行三个简单 SQL 查询的代码。前两个查询效果很好,但第三个查询效果不佳。实际上,我的代码的一部分似乎在第二次查询后根本没有执行,因为控制台中没有打印“yes”。
我尝试通过注释掉第二个查询执行行来编译我的代码,然后执行代码的末尾。有什么想法吗?
import java.sql.*;
public class Main {
public static void main(String[] args) {
//connection to DB
Class.forName("org.postgresql.Driver");
Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/Benerator","postgres","newPassword");
//print the first two columns of table bank_card_people
PreparedStatement stmt = con.prepareStatement("select * from public.bank_card_people");
ResultSet res = stmt.executeQuery();
while(res.next()){
System.out.println(res.getString(1)+ " " + res.getString(2));}
//add a line to the same table
String SQL = "insert into public.bank_card_people (\"first-name\", \"last-name\", \"card-number\") VALUES ('example','example','example')";
PreparedStatement stmt2 = con.prepareStatement(SQL);
stmt2.executeQuery();
// is supposed to print all the databases
PreparedStatement stmt3 = con.prepareStatement("SELECT datname FROM pg_database WHERE datistemplate = false");
ResultSet res2 = stmt3.executeQuery();
System.out.println("yes");
while(res2.next()){
System.out.println(res2.getString(1));}
这是输出:
User One
User Two
User Three
example example
example example
No results were returned by the query.
这是我注释掉该行时的输出:stmt2.executeQuery();
User One
User Two
User Three
example example
example example
yes
postgres
Benerator
最佳答案
INSERT 语句不能由 executeQuery
执行,而是由 executeUpdate
执行。
此外,Connection、Statement 和 ResultSet 必须是 .close()
d,最好使用 try-with-resources 来完成,这样即使出现异常或返回也能保证关闭。
它还有助于命名,因为它引入了新 block 。
//connection to DB
Class.forName("org.postgresql.Driver");
try (Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/Benerator","postgres","newPassword")) {
//print the first two columns of table bank_card_people
try (PreparedStatement stmt = con.prepareStatement("select * from public.bank_card_people");
ResultSet res = stmt.executeQuery()) {
while (res.next()) {
System.out.println(res.getString(1)+ " " + res.getString(2));
}
}
//add a line to the same table
String sql = "insert into public.bank_card_people (\"first-name\", \"last-name\", \"card-number\") VALUES ('example','example','example')";
try (PreparedStatement stmt2 = con.prepareStatement(sql)) {
int updateCount = stmt2.executeUpdate();
}
// is supposed to print all the databases
try (PreparedStatement stmt3 = con.prepareStatement("SELECT datname FROM pg_database WHERE datistemplate = false"));
ResultSet res2 = stmt3.executeQuery()) {
System.out.println("yes");
while(res2.next()){
System.out.println(res2.getString(1));
}
}
}
关于java - 为什么 PostgreSQL 查询后部分 Java 代码没有执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51858721/