tags:

views:

79

answers:

2

how can i replace hardcoded number with variable in this java statement which is accessing the mysql datatabase using jdbc. the query is executed using executeQuery(query)

here is the java statement

String query = "select * from TableA where num = '1233' ";

i need to replace this 1233 with a variable in this statement.

any help appreciated

Regards,

+7  A: 

If you can use prepared statement, you'll be safer (no risk of SQL injection):

 Connection con = getMyConnection();
 try {
  PreparedStatement ps = con.prepareStatement("select * from TableA where num = ?");
  try {
   ps.setLong(1, number);
   ResultSet rs = ps.executeQuery();
   while(rs.next()) {
    //TODO
   }
  } finally {
   ps.close();
  }
 } finally {
  con.close();
 }
Jerome
@OP: Using a `PreparedStatement` like this solves a number of issues for you (escaping special characters in strings, formatting timestamps correctly, etc.), definitely the way to go. Also, you can re-use `PreparedStatement` instances if you need to (in a loop, for instance).
T.J. Crowder
In addition to being safer, the driver or the pool implementation may use a query cache that improves performance.
Maurice Perry
what if the statement is not executeQuery(query)but executeUpdate(query)examplequery = " create view view1 as select * from table where num = '1233'";
silverkid
i.e how to use prepared statement in case of update queries
silverkid
Same thing. Read the documentation.
Bombe
use ps.executeUpdate() in case of update queries.
Jerome
A: 

Are you using hibernate? If yes this is how you should go
supose str is the string/integer you want to replace then
get the str by requestobject and continue by using the following code
try {
SessionFactory sessionfactory = new Configuration().configure().buildSessionFactory();
session = sessionfactory.openSession();
String query = "from Contact c where name='"+str+"'";
Query query1 = session.createQuery(query);
list = query1.list();
System.out.println("Number of users in the system :- "+list.size());
for (Contact contact : list) {
System.out.println(contact.getId()+" : "+contact.getName()+" : "+ contact.getRole()+ " : "+ contact.isEnable());
}

akellakarthik
Even with Hibernate, you should use query parameters. In Hibernate it's achieved via the `org.hibernate.Query`'s `set*` methods, which is later translated by Hibernate to a `PreparedStatement`. See Jerome's answer for all the reasons why.
Eli Acherkan