There is a good way to use a prepared statement in java where there is the possibility to have a probability that some parameter can be or not be set?
Let’s assume I have a complete query like this one:
SELECT * FROM Table1 WHERE Field1='....' AND Field2='....' AND Field3='....'
Then in my program I would like to do something like that (I know it’s not possible the way I write)
// part of code where I have 3 variable set by some logic and the query itself
//.........
String Query = "SELECT * FROM Table1 WHERE Field1=? ";
PreparedStatement s = conn.prepareStatement();
s.setString(1, Field1Var);
if (Field2Var != Value)
{
Query += " AND Field2=? ";
s.setString(2, Field2Var);
}
if (Field3Var != Value3)
{
Query += " AND Field3=? ";
s.setString(3, Field3Var);
}
s = conn.prepareStatement(query);
How can I achieve it without write many different queries?
Or you can write a “NamedPreparedStatement” like I did. (https://gist.github.com/1978317)