gpt4 book ai didi

java - JDBC 从其中 x=(?) 选择 *

转载 作者:行者123 更新时间:2023-12-01 22:06:10 25 4
gpt4 key购买 nike

我正在尝试创建一种从数据库中检索客户并将其存储在对象中的方法。但由于某种原因我的sql语句不起作用。

这是我的方法。

    public class CustomerDAO {

private String url = "jdbc:h2:tcp://localhost/project;IFEXISTS=TRUE";

Set<Customer> customerCollection = new TreeSet<>();


public Customer loginCustomer(String user,String pass) throws SQLException{

String sql = "SELECT * FROM Customers WHERE USERNAME=(?) AND PASSWORD=(?) ;";

try(
//get connection form database
Connection dbCon = JdbcConnection.getConnection(url);
//create a statement
PreparedStatement stmt = dbCon.prepareStatement(sql);
){

stmt.setString(1, user);
stmt.setString(2, pass);

ResultSet rs = stmt.executeQuery();

Customer c = new Customer(rs.getString("username"), rs.getString("name"), rs.getString("email"),
rs.getString("address"), rs.getString("creditCardDetails"), rs.getString("password"));


if(c.getUsername().contains(user))
return c;
else
return null;


}catch (SQLException ex){
throw new RuntimeException(ex);
}

}

我用这个测试了

        public static void main(String[] args) throws SQLException {

CustomerDAO dao = new CustomerDAO();

Customer c = dao.loginCustomer("jesus", "1234");

System.out.println(c.getName());
System.out.println(c.getPassword());
System.out.println(c.getAddress());



}

}

但我收到这些错误。

        Exception in thread "main" java.lang.RuntimeException: org.h2.jdbc.JdbcSQLException: No data is available [2000-187]
at DAO.CustomerDAO.loginCustomer(CustomerDAO.java:54)
at web.NewMain.main(NewMain.java:25)
Caused by: org.h2.jdbc.JdbcSQLException: No data is available [2000-187]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
at org.h2.message.DbException.get(DbException.java:179)
at org.h2.message.DbException.get(DbException.java:155)
at org.h2.message.DbException.get(DbException.java:144)
at org.h2.jdbc.JdbcResultSet.checkOnValidRow(JdbcResultSet.java:3186)
at org.h2.jdbc.JdbcResultSet.get(JdbcResultSet.java:3192)
at org.h2.jdbc.JdbcResultSet.get(JdbcResultSet.java:3209)
at org.h2.jdbc.JdbcResultSet.getString(JdbcResultSet.java:302)
at DAO.CustomerDAO.loginCustomer(CustomerDAO.java:43)
... 1 more
Java Result: 1

直接从数据库控制台运行该语句效果很好。例如

SELECT * FROM Customers WHERE USERNAME='jesus' AND PASSWORD='1234' ;

最佳答案

您必须将光标移动到下一行:添加

rs.next();

之后:

 ResultSet rs = stmt.executeQuery();

关于java - JDBC 从其中 x=(?) 选择 *,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32730971/

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