1

I'm using below code to print columns from a tables using PreparedStatement:

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

    String url = "jdbc:mysql://localhost/javatesting";

    Connection con = DriverManager.getConnection(url, "root", "password");

    PreparedStatement preparedStatement = con.prepareStatement("Select ?,?,? from test where salary> ?");

    preparedStatement.setString(1, "name");
    preparedStatement.setString(2, "dept");
    preparedStatement.setString(3, "salary");
    preparedStatement.setInt(4, 25000);

    ResultSet resultSet = preparedStatement.executeQuery();

    while(resultSet.next()){
        System.out.println(resultSet.getString("name")+","+resultSet.getString("dept")+","+
                resultSet.getString("salary"));
    }

The output of above code looks like this:

name,dept,salary
name,dept,salary
name,dept,salary

There are actual(valid) values in the table, still I end up printing the column names instead of values.

The output that I'm expecting to get printed looks something like this:

Ben,IT,30000
Marie,BPO,35000
Subash,IT,30000
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Math
  • 31
  • 6

1 Answers1

3

The problem is that the PreparedStatement escapes the values that are passed via a ?.

So name becomes "name" and SELECT "name" always returns name.

You should change your query:

SELECT name, dept, salary FROM test WHERE salary > ?
preparedStatement.setInt(1, 25000);
Daniel
  • 1,426
  • 1
  • 11
  • 24