我目前在使用此代码时遇到一些问题:
public User validateUser(String username, String password) {
boolean found = false;
Connection c = DBHelperClass.getConnection();
String query = "Select * from user where username= '?' and password= '?' ";
if (c != null) {
try {
PreparedStatement inserter = c.prepareStatement(query);
inserter.setString(1, username);
inserter.setString(2, password);
System.out.println("help: "+query);
ResultSet resultSet = inserter.executeQuery(query);
while (resultSet.next()) {
this.userId = resultSet.getInt("userId");
this.username = resultSet.getString("usrname");
this.password = resultSet.getString("password");
this.address = resultSet.getString("address");
this.email = resultSet.getString("email");
this.phone = resultSet.getInt("phone");
found = true;
}
} catch (SQLException ex) {
Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
}
}
return this;
}
我得到的错误是:
java.sql.SQLException:参数索引超出范围(1>数 参数,即0)
从阅读其他答案我尝试改变'?'标签但未能这样做。
答案 0 :(得分:5)
更改
Select * from user where username= '?' and password= '?'
到
Select * from user where username= ? and password= ?
无需添加'
<强>更新强>:
并将inserter.executeQuery(query);
更改为inserter.executeQuery();
答案 1 :(得分:1)
java.sql.SQLException:参数索引超出范围(1&gt;数 参数,即0)
您收到此错误是因为您拨打了executeQuery(query)
而不是executeQuery()
,因此它认为您的查询不需要任何参数,但您提供的不止一个导致此异常,因此只需使用inserter.executeQuery()
。
已经提到的第二个错误是,您不需要在查询中使用引号,它应该只是Select * from user where username= ? and password= ?
答案 2 :(得分:0)
错误消息表示查询中的参数为零。这是因为你使用撇号转义了问号字符。 在不使用问号的撇号的情况下重写查询。
String query = "Select * from user where username= ? and password= ?";
答案 3 :(得分:0)
感谢帮助人员,这是固定代码:
public User validateUser(String username, String password) {
boolean found = false;
Connection c = DBHelperClass.getConnection();
String query = "Select * from user where username= ? and password= ? ";
if (c != null) {
try {
PreparedStatement inserter = c.prepareStatement(query);
inserter.setString(1, username);
inserter.setString(2, password);
System.out.println("help: "+query);
ResultSet resultSet = inserter.executeQuery();
while (resultSet.next()) {
this.userId = resultSet.getInt("userId");
this.username = resultSet.getString("username");
this.password = resultSet.getString("password");
this.address = resultSet.getString("address");
this.email = resultSet.getString("email");
this.phone = resultSet.getInt("phone");
found = true;
}
} catch (SQLException ex) {
Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
}
}
return this;
}
我需要改变的一切就是删除&#39;&#39;在附近?并将executeQuery(query)更改为executeQuery()
万分感谢!