Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

sql - SQLite Query With Parameters Not Working in Java

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...