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
278 views
in Technique[技术] by (71.8m points)

java - How to use dynamic table name in SELECT query using JDBC

I have 5 or table table to query from

my syntax i like this

String sql2 = "SELECT * FROM ? WHERE Patient_ID = ?";

pst = conn.prepareStatement(sql2);

        System.out.println("SQL before values are set "+sql2);
        System.out.println("The values of table/test name recieved in TestPrint stage 1 "+tblName);
        System.out.println("The values of test name recieved in TestPrint stage 1 "+key);
        // values are outputted correctly but are not getting set in the query

        pst.setString(1, tblName);
        pst.setLong(2, key);
ResultSet rs2 = pst.executeQuery(sql2);

        while(rs2.next()){

            String ID = rs2.getString("ID");

            jLabel35.setText(ID);
            jLabel37.setText(ID);
            jLabel38.setText(ID);
       // them print command is initiated to print the panel
}

The problem is when i run this i get an error saying ".....you have and error in SQL syntax near ? WHERE Patient_ID = ?"

When i output the sql using system.out.println(sql2);

values are not set in sql2

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

When you prepare a statement, the database constructs an execution plan, which it cannot do if the table is not there. In other words, placehodlers can only be used for values, not for object names or reserved words. You'd have to rely on Java to construct your string in such a case:

String sql = "SELECT * FROM `" + tblName + "` WHERE Patient_ID = ?";

pst = conn.prepareStatement(sql);
pst.setLong(1, key);
ResultSet rs = pst.executeQuery(sql);

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

...