简体   繁体   English

使用PrepareStatement获取具有可配置表名的数据

[英]Using PrepareStatement to get data with configurable table name

I'm trying to get some data from Oracle 11.2 using java and jdbc driver. 我正在尝试使用java和jdbc驱动程序从Oracle 11.2获取一些数据。

My goal is to get data from database using CallableStatement, but with no luck - I'm not able to put table name as parameter. 我的目标是使用CallableStatement从数据库中获取数据,但没有运气-我无法将表名作为参数。 I would like to have configurable table name in query. 我想在查询中使用可配置的表名。 However, it would be good to keep it sanitized. 但是,最好保持消毒状态。

Here is an example.. 这是一个例子。

public void getData() throws SQLException {

    Connection conn = Config.getSQLConnection();
    String query = "SELECT * FROM ?";
    PreparedStatement st = conn.prepareStatement(query);
    st.setString(1, Config.DATATABLE_NAME);
    ResultSet rs = st.executeQuery();

    if (rs.next()) {
        System.out.println("SUCCESS");
        System.out.println("ID:" + rs.getString("ID"));
    } else {
        System.out.println("FAILURE");
    }
}

Is this the way it should work? 这是应该起作用的方式吗? Or am I missing something, or misused it? 还是我遗漏了某些东西或滥用了它?

A CallableStatement is used to make call to stored procedures. CallableStatement用于调用存储过程。

From javadoc : javadoc

The interface used to execute SQL stored procedures 用于执行SQL存储过程的接口

Use a PreparedStament instead for a normal select. 请使用PreparedStament进行常规选择。

As an additional note don't pass the name of the table as parameter. 另外请注意,请勿将表名称作为参数传递。 Create the query using concatenation. 使用串联创建查询。

Instead of 代替

String query = "SELECT * FROM ?";

use 采用

String query = "SELECT * FROM " + Config.DATATABLE_NAME;

You should use PreparedStatement instead of CallableStatement. 您应该使用PreparedStatement而不是CallableStatement。 CallableStatement is an interface which is used to call stored procedures. CallableStatement是用于调用存储过程的接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM