-1

i have some jsp file. it has some variables. i want to use these varibles inside a mysql query as follows.

String given_session="monsoon";
String given_year="2012";
// note above two will be dynamically added.

ResultSet rs11 = (ResultSet) st11.executeQuery("show tables like '%_Assessment_" + given_session + "_" + given_year+"'");

I got the following exception :

 java.sql.SQLException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%_Assessment_Monsoon_2013''
Paul Vargas
  • 41,222
  • 15
  • 102
  • 148

1 Answers1

3

There is a better and more elegant way.

String tableNamePattern  = "%_Assessment_" + session + "_" + year;

DatabaseMetaData databaseMetaData = conn.getMetaData();
ResultSet rs = databaseMetaData.getTables(null, null, tableNamePattern, 
                                          null);
while(rs.next()) {
    String tableName = rs.getString("TABLE_NAME");
    ...
}

Moreover, you must know the best practices of programming in Java because what you are using in your code is not smart. You can see a lot in Java Collected Practices.

Andrzej Bobak
  • 2,106
  • 3
  • 28
  • 36
Paul Vargas
  • 41,222
  • 15
  • 102
  • 148