I am making a JAVA program where I have placed some values in a database with a table new_table. It has columns: Username, Password, and Name.
I am taking input from the user for a username and password through the console and check if it matches a row in the table.
Statement st=Myconn.createStatement();
ResultSet rs=st.executeQuery("select * from new_table");
String getusnm=rs.getString("username")
String get pswd=rs.getString("password");
The next thing is, I want to display the name of the users from the table if the username and password match. So, how do I get the name of the user using the same result set as a String?
I used:
String getname=rs.getString("name","where usnm = user"); // user is the String inputted from the console
but it doesn't seem to work.
Kindly help me out with this.
Thanks.
You should be using a WHERE
clause in your SQL query which restricts by username and password:
String sql = "SELECT * FROM new_table WHERE usnm = ? AND pass = ?";
PreparedStatement st = conn.prepareStatement(sql);
st.setString(1, username);
st.setString(2, password);
ResultSet rs = st.executeQuery();
if (rs.next()) {
String username = re.getString("usnm");
}
Note that in general it is bad practice to store clear text passwords in your database table. More typically, you would be hashing incoming passwords before inserting them. Then, to verify an incoming user password, you would also hash it, and then compare the two hashes.