选择查询中的JDBC PreparedStatement和参数(?) [英] JDBC PreparedStatement and parameters (?) in select query

查看:313
本文介绍了选择查询中的JDBC PreparedStatement和参数(?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与oracle数据库有这样的连接:

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

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

选择"supplier_id",供应商名称FROM供应商WHERE Supplier_id = ?

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

代替

选择供应商ID,供应商名称,从供应商处供应商ID = ?

select supplier_id, supplier_name FROM supplier WHERE supplier_id = ?

由于这个结果,我没有从表cores中获得对应于provider_id的值,而是字符串"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?

推荐答案

无法以这种方式创建动态查询,必须使用常规的字符串操作.参数只能用于字符串,数字等值,而不能用于名称.

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");

这篇关于选择查询中的JDBC PreparedStatement和参数(?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆