0

I have a very basic MySQL Database. This is the query I used to create it:

CREATE TABLE SC_Users(
ID int(11) NOT NULL AUTO_INCREMENT, 
PRIMARY KEY (ID), 
Username varchar(255) NOT NULL, 
Class varchar(255) NOT NULL
)

I get a ResultSet by querying my database with this:

SELECT * FROM SC_Users

I want to be able to search for a username and then find the corresponding class of that username. How would I do this without using a different query?

I know its possible to find it easily by using:

SELECT * FROM SC_Users WHERE `Username` = Username

But I would prefer to use only 1 query if possible to find any value of a user I want. Thanks in advance for the help!

2
  • You can achieve it by retrieving all your data in a ResultSet, then add all the values in a List<MyClass> only if they meet the conditions you need. Commented Jun 10, 2012 at 4:02
  • 4
    Why would you want to get all that data from the database and spend all that time in java iterating over it? Commented Jun 10, 2012 at 4:05

1 Answer 1

3

You can simply use PreparedStatement for your purpose.

    PreparedStatement pst=null;
    ResultSet rs=null;
    String userName = "someUser";
    String userClass;
    pst=con.prepareStatement("select * from SC_users where Username=? ");
    pst.setString(1,userName);
    rs=pst.executeQuery();
        if(rs.next())
        {
            userClass=rs.getString("Class");
        }
Sign up to request clarification or add additional context in comments.

Comments

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.