String q = "SELECT attr FROM students foo =? AND bar = ?";
PreparedStatement s= connection.prepareStatement(q);
s.setString(1,"a");
s.setString(2."b");
ResultSet rs = s.executeQuery();
if(rs.next())
{
System.out.println("aba");
}
else
{
System.out.println("zab");
}
I’m not entirely sure, but my interpretation is that it performs query to find “attr” from “students” where foo is something and bar is something. In case of successful results from query it prints out aba, otherwise it will print out zab.
Correct me if i’m wrong.What s.setStrings(1,”a”) are for? What exactly question mark stands for?
You are mostly right. If there is at least one row in the
studentstable, with fieldfoo='a'andbar='b', this prints outaba, if no such line exists, it prints outzabThe question marks and the0
.setString(1,"a")statements are closely related. The?denotes a parameter (placeholder, if that is more convenient to grasp) to the query, and thes.set<datatype>()methods ‘fill these in’. The first parameter specifies the parameter to fill in, the second specifies the value.Recommended reading: Using PreparedStatements