Giri
Giri

Reputation: 137

How do I use a dynamic object in JDBC application

The query is working fine in MySQL db. I have this query in my JDBC application. And I'm getting some compile time error.
My input objects are s1 and s2, where s1 contains january and s2 contains 2013. Both datatypes are VARCHAR. I am facing a problem in quotes. Please suggest some correction.

String QueryString = "SELECT reading,totalcost,paiddate,receiptnumber
FROM userseven WHERE (readingmonth = '"+s1+"' AND readingyear='"+s2+"'");

Upvotes: 0

Views: 50

Answers (1)

maks
maks

Reputation: 6006

You should better use PreparedStatementfor such purpose. So your query will look like this:

 String QueryString = "SELECT reading,totalcost,paiddate,receiptnumber FROM userseven WHERE
 readingmonth = ? AND readingyear= ?;

Then create PreparedStatement from connection object like this:

PreparedStatement stmt = conn.prepareStatement(QueryString);

And then set parameters for that statement like this:

stmt.setString(1, s1);
stmt.setString(2, s2);

Such modifications will save you from potential sql injection and simply simplify the process of building complex query

Upvotes: 2

Related Questions