0

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.

2

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Is the string in "sql" case sensitive?
If you're asking if it matters whether you use SELECT, select, or maybe SeLeCt, no, it doesn't matter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.