gpt4 book ai didi

java - JDBC 预处理语句 select from table where

转载 作者:搜寻专家 更新时间:2023-10-30 23:05:48 24 4
gpt4 key购买 nike

我正在尝试编写一个 JDBC SQLite 准备语句,它将返回 customerID 与传入的行匹配的行。我的方法返回空指针异常。

我不太了解 JDBC、SQLite 或准备好的语句,但据我所知,我拥有我需要的一切,但无法弄清楚为什么它不起作用。我的代码如下:

public static void CustomersSelectWhere(JPanel customers, int CustID)
{
CustomersTable();
String [] entries = new String[7];
Connection c = null;
PreparedStatement pstmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:WalkerTechCars.db");
c.setAutoCommit(false);

String query = "SELECT * FROM CUSTOMERS WHERE CUSTID=? " ;

ResultSet rs = pstmt.executeQuery( query );

pstmt = c.prepareStatement(query);
pstmt.setInt(1, CustID);
pstmt.executeUpdate();
c.commit();



while ( rs.next() ) {
int custId = rs.getInt("custID");
String phone = rs.getString("phone");
String surname = rs.getString("surname");
String firstname = rs.getString("firstname");
String home = rs.getString("home");
String address = rs.getString("address");
String postcode = rs.getString("postcode");

customers.add(customersTableSingle(Integer.toString(custId), firstname, surname, phone, home, address, postcode, false, customers ));


}
rs.close();
pstmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}

}

}

最佳答案

你已经定义了

PreparedStatement pstmt = null;

准备好的语句应该是从连接创建的。因为你的准备语句是空的,你正试图调用 ResultSet rs = pstmt.executeQuery( query );这就是NPE的原因。

关于java - JDBC 预处理语句 select from table where,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26685830/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com