0

I am working on a project for a class and am a beginner at using the JDBC. For one part, my instructor wants us to "provide a query menu that allows a user to input query command and retrieve information from the database." I have researched quite a bit and am unable to find a way to do this. Most examples I have seen already know what the user is going to be querying. If I am allowing the user to query anything, how can I return the correct information? The code I have so far is below.

System.out.println("What table do you wish to query?");
table = scan.nextLine();
System.out.println("What values do you wish to query? Type them separated by commas. If you wish to select all values, please type a *.");
values = scan.nextLine();
System.out.println("Type the conditions for your WHERE clause, excluding the keyword WHERE.");
conditions = scan.nextLine();
query = "SELECT " + values + " FROM " + table + "WHERE " + conditions;
try {
    stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery(query);
    while (rs.next()) {
        if(values != "*")
           String results = rs.getString(values);
    }

There is where I am stuck because I have no idea what the user is going to query so I do not know what to put in the while loop, as in this example where they know the user is looking for last names.

rs = stmt.executeQuery("SELECT Lname FROM Customers WHERE Snum = 2001");
while ( rs.next() ) {
    String lastName = rs.getString("Lname");
    System.out.println(lastName);
}

Any help or suggestions would be greatly appreciated.

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
Ashlee Berry
  • 75
  • 1
  • 7

1 Answers1

0

I think you have the basics so I will just give you the pseduocode for a possible way to do it and let you fill in the blanks.

1) input user values and put in an array (VALUESARRAY)
2) validate values against table field names (exit if invalid)
3) prepare query
4) execute query
5) loop through the VALUEARRAY and get appropriate value from the result set     
   (same as you did in your example).

I think #5 is what you weren't sure how to do, but using the array should resolve that.

TDWebDev
  • 86
  • 5