Reputation: 13
I am trying to allow the user to change the password if he enters the right username. The username is drawn from the database and compared to the username the user enter in a form. My problem is after the validation is done the UPDATE statement is not producing any result. Can someone help me out please?
String un = request.getParameter("username");
String psw = request.getParameter("password");
String cPsw = request.getParameter("cpassword");
Connection con = ConnectionHelper.getConnection();
try {
ResultSet rs = userList(con);
if (rs.next()) {
String n = rs.getString("username");
if (n.equals(un)) {
out.print("Password match");
String updateQuery = "UPDATE RegisteredUserInfo SET password ='"
+ cPsw + "'WHERE username ='" + un + "'";
PreparedStatement ps1 = con.prepareStatement(updateQuery);
ps1.executeQuery();
ServletContext context = getServletContext();
RequestDispatcher rd = context
.getRequestDispatcher("/Welcome.jsp");
rd.forward(request, response);
}
}
} catch (SQLException sx) {
out.println();
}
}
public ResultSet userList(Connection con) throws SQLException {
PreparedStatement ps;
ResultSet rs;
String matchingUname = "SELECT username FROM RegisteredUserInfo";
ps = con.prepareStatement(matchingUname);
rs = ps.executeQuery();
return rs;`
Upvotes: 1
Views: 1848
Reputation: 109613
You need to call executeUpdate()
for SQL UPDATE (or INSERT/DELETE).
String updateQuery = "UPDATE RegisteredUserInfo SET password = ?"
+ " WHERE username = ?";
PreparedStatement ps1 = con.prepareStatement(updateQuery);
ps1.setString(1, cPsw);
ps1.setString(2, un);
ps1.executeUpdate();
Also use the PreparedStatement as above. Look for SQL Injection, also escapes '
.
Upvotes: 1
Reputation: 46871
Try with ps1.execute();
or ps1.executeUpdate()
instead of ps1.executeQuery();
Call con.commit();
to commit the changes and Don't forget to close the resources in the end.
Check the return type of below methods to make sure that data is inserted properly.
Executes the SQL query in this PreparedStatement object and returns the ResultSet object generated by the query.
Executes the SQL statement in this PreparedStatement object, which must be an SQL INSERT, UPDATE or DELETE statement; or an SQL statement that returns nothing, such as a DDL statement.
Ream more about Difference between execute, executeQuery, executeUpdate
e.printStackTrace()
while development.Upvotes: 2