user225269 user225269 - 1 month ago 9
Java Question

mysql select query in java

I'm new to connecting java with a mysql database. What's wrong with my query here:

PreparedStatement statement = conn.prepareStatement("SELECT * FROM q_table, choices, answers WHERE q_table.QID='" + number_input + "' AND choices.CID='" + number_input + "' AND answers.AID='" + number_input + "'");

Answer

In your statement " ... q_table.QID='" + number_input + "' AND ... the variable number_input is enclosed in a single quote ('). This is used for string lieterals. If you remove the single quote it should work:

 String prest= "SELECT * FROM q_table, choices, answers  WHERE questions.QID=? AND choices.CID=? AND answers.AID=?";

 prest.setInt(1,1980);
 prest.setInt(2,2004);
 .
 .
 ResultSet rs = prest.executeQuery();
 while (rs.next()){
     String mov_name = rs.getString(1);
     int mov_year = rs.getInt(2);
     count++;
     System.out.println(mov_name + "\t" + "- " + mov_year);
 }
 System.out.println("Number of records: " + count);
 prest.close();
 con.close();