我正在开发一个WEB项目,我想让用户注册,所以在用户写完他的详细信息(用户名,密码,昵称......)后,我想查看用户名或昵称他输入是唯一的(不存在于Users表中),所以在servlet中我写道:
try {
Context context = new InitialContext();
BasicDataSource ds = (BasicDataSource) context
.lookup(getServletContext().getInitParameter(UAppConstants.DB_DATASOURCE) + UAppConstants.OPEN);
Connection conn = ds.getConnection();
PreparedStatement stmt;
try{
System.out.println("1");
stmt = conn.prepareStatement(UAppConstants.SELECT_USER_BY_NICKNAME_STMT);
System.out.println("2");
stmt.setString(1, _nickname);
//here some other code
}catch (SQLException e) {
System.err.println(e.getMessage());
}
//here some other code
}
catch (SQLException | NamingException e) {
getServletContext().log("Error while closing connection", e);
response.sendError(500);// internal server error
}
UAppConstant.java:
public final String SELECT_USER_BY_NAME_STMT = "SELECT * FROM USERS " + "WHERE username=?";
public final String SELECT_USER_BY_NICKNAME_STMT = "SELECT * FROM USERS" + "WHERE nickname=?";
并且在sql表中有列username,nickname。
问题是它在控制台中打印1但从不打印2,而是打印:
Syntax error: Encountered "=" at line 1, column 34.
我查看了servlet中的所有“=”,所有这些都是正确的语法!
感谢帮助者:)
答案 0 :(得分:2)
您可能忘记在prepare语句模板中指定参数编号。因此 PreparedStatement 无法确定要设置哪个参数来代替?。还" "在 USERS 和 WHERE
之间缺失所以,而不是:
"SELECT * FROM USERS" + "WHERE nickname=?"
你应该写:
"SELECT * FROM USERS " + "WHERE nickname=?1"
同样地,而不是:
"SELECT * FROM USERS " + "WHERE username=?"
你应该写:
"SELECT * FROM USERS " + "WHERE username=?1"