JDBC PreparedStatement and parameters (?) in select query [duplicate]

旧时模样 提交于 2020-01-05 12:57:12

问题


I have a connection with oracle database like this:

String selectSQL = "SELECT ?,supplier_name FROM supplier WHERE supplier_id = ?";
        PreparedStatement preparedStatement = con.prepareStatement(selectSQL);
        preparedStatement.setString(1, "supplier_id");
        preparedStatement.setInt(2, 1);
        ResultSet rs2 = preparedStatement.executeQuery();

        while (rs2.next()) {
            String userid = rs2.getString(1);
            String username = rs2.getString(2);
            System.out.println(userid);
            System.out.println(username);
        }
        con.close();
    };

The problem is that the second parameter is passed like I want which means that

supplier_id = 1

but I have a problem with the first parameter. Each time only the string is beeing passed so my query looks like

select "supplier_id", supplier_name FROM supplier WHERE supplier_id = ?

instead of

select supplier_id, supplier_name FROM supplier WHERE supplier_id = ?

Because of that as a result I don't get the value from the table coressponding to supplier_id but the string "supplier_id". What am I doing wrong? What should I change to get the value not string?


回答1:


It is not possible to create dynamic queries this way, you have to use the normal string operations. Parameters can only be used for values, like Strings, Numbers, etc., not for names.

In your case it would be possible to do something like

String sqlTemplate = "SELECT <id_column>,supplier_name FROM supplier WHERE supplier_id = ?";
String selectSQL = sqlTemplate.replace("<id_column>", "supplier_id");


来源:https://stackoverflow.com/questions/46016011/jdbc-preparedstatement-and-parameters-in-select-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!