JSF 中使用PreparedStatement的setString问题
下面用户登陆验证代码运行后,把正确的用户名和密码输入后,与数据库存放的用户名和密码核对总是不成功,请老师知道一下:
14. public class UserBean {
15. private String name;
16. private String password;
17. private boolean loggedIn;
18. private Logger logger = Logger.getLogger( "com.corejsf ");
19.
public void doLogin() throws SQLException, NamingException {
50. Context ctx = new InitialContext();
51. if (ctx == null) throw new NamingException( "No initial context ");
53. DataSource ds = (DataSource) ctx.lookup ( "java:comp/env/jdbc/mydb ");
54. if (ds == null) throw new NamingException( "No data source ");
56. Connection conn = ds.getConnection();
57. if (conn == null) throw new SQLException( "No connection ");
59. try {
60. PreparedStatement passwordQuery = conn.prepareStatement(
61. "SELECT password from Users WHERE username = ? ");
63. passwordQuery.setString(1, name);
65. ResultSet result = passwordQuery.executeQuery();
67. if (!result.next()) return;
68. String storedPassword = result.getString( "password ");
69. loggedIn = password.equals(storedPassword.trim());
70. }
71. finally {
72. conn.close();
73. }
74. }
75. }
但将 "SELECT password from Users WHERE username = ? " 改为 "SELECT password from Users WHERE username = 'name ' ",并且去掉 passwordQuery.setString(1, name);这行后,就可以和数据库存放的用户名和密码核对成功。 这是为什么?谢谢大家!
[解决办法]
the value of name is null