-3

I want to pass strings as parameters to my JDBC program. The code works fine for INT type inputs but goes to catch block on string type inputs.

I wanted to modify the program such that it can capture all types of inputs at random. Because, I need to run the following java prog. in bash script. So once class file is generated, i supposed to provide random inputs to the program and obtain the output...

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mysql.jdbc.Statement;

public class JDBC_run {

    public static void main(String[] args) throws Exception {

        Connection conn = null;
    //  int var = 123050044 ;
        String var = "sir"; 

        Class.forName("com.mysql.jdbc.Driver"); 
        conn = DriverManager.getConnection( "jdbc:mysql://localhost/test?user=root&password=root");
        ResultSet rs;
        System.out.println("Connected?");
        try{
          Statement st = (com.mysql.jdbc.Statement) conn.createStatement();
          rs = st.executeQuery("SELECT type FROM Table_new WHERE id = " + var);
          while ( rs.next() ) {
                String lastName = rs.getString("type");
                System.out.println(lastName);
            }
          }

      catch(SQLException s){
          System.out.println("wrong !!");
          }
}
}

For int var = 123050044, the output is

Connected?
student

For String var = "sir", the output is

Connected?
wrong !!
Roman C
  • 49,761
  • 33
  • 66
  • 176
user1709815
  • 265
  • 1
  • 2
  • 9
  • 1
    When you have a question here, it is a complete waste of time to just use vague statements like 'unable to execute'. When you get an exception, it is a complete waste of time to just print 'wrong !!'. Print the actual exception and its stack trace. Until you do that and post the results here (edit them into your post), your question is just a guessing game. – user207421 Apr 20 '13 at 01:04

1 Answers1

1
SELECT type FROM Table_new WHERE id = " + var

Works fine for int. When use String above query should be something like below (Note: This is prone to SQL Injection, use PreparedStatement instead of plain SQL Strings.)

SELECT type FROM Table_new WHERE id = ' " + var +"'"

otherwise you will get SQLException (I guess that is the case happening for you).

Printing exception in catch block will give you more clues.

kosa
  • 65,990
  • 13
  • 130
  • 167
  • 1
    Just to add to the SQL injection note above - you can look into PreparedStatements. – jcadcell Apr 19 '13 at 19:30
  • To avoid all risk of sql injection, you should either use prepared statements, or an sql escaping method (see for example http://stackoverflow.com/questions/881194/how-to-escape-special-character-in-mysql/6478616#6478616) – Walid Apr 19 '13 at 19:31
  • SELECT type FROM Table_new WHERE id = ' " + var +"'" : is giving no out put only Connected? is apearing – user1709815 Apr 19 '13 at 19:34