参数无法在Java中运行的SQLite查询 [英] SQLite Query With Parameters Not Working in Java

查看:74
本文介绍了参数无法在Java中运行的SQLite查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,从给定表和列字符串的数据库中选择.

I have a program that selects from a database given a table and column string.

public void selectAllFrom(String table, String column){
        String sql = "SELECT ? FROM ?";

        try (Connection conn = this.connect();
             PreparedStatement pstmt  = conn.prepareStatement(sql)){
            pstmt.setString(1, column);
            pstmt.setString(2, table);

            ResultSet rs = pstmt.executeQuery();

            while (rs.next()){
                System.out.println(rs.getString(column));
            }

        } catch (SQLException e){
            System.out.println(" select didn't work");
            System.out.println(e.getMessage());
        }
    }

由于某种原因,它无法正常工作,并且可以捕获

For some reason it is not working and it is going right to catch

这也是connect()函数:

Here is the connect() function as well:

private Connection connect(){
    Connection conn = null;
    // SQLite connection string
    String url = "jdbc:sqlite:C:/sqlite/db/chinook.db";

    try{
    // creates connection to the database
    conn = DriverManager.getConnection(url);
    System.out.println("Connection to SQLite has been established");
    } catch (SQLException e){
        System.out.println(e.getMessage());
        System.out.println("Connection didn't work");
    } 

    return conn;
}

我知道问题不在于数据库,因为我可以运行其他不带参数的选择查询.是参数给了我这个问题.谁能说出问题所在?

I know the problem is not with the database because I'm able to run other select queries without parameters. It is the parameters that are giving me the problem. Can anyone tell what the problem is?

推荐答案

表或列名称不能用作PreparedStatement的参数.它必须是硬编码的.

A table or column name can't be used as a parameter to PreparedStatement. It must be hard coded.

String sql = "SELECT " + column + " FROM " + table;

您应该重新考虑设计,以使这两个常量保持不变并参数化列值.

You should reconsider the design so as to make these two constant and parameterize the column values.

这篇关于参数无法在Java中运行的SQLite查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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