如何在使用JDBC的SELECT查询中使用动态表名

时间:2014-02-09 20:55:46

标签: java mysql select dynamic tablename

我有5或表格来从\

查询

我的语法我喜欢这个

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
}

问题是,当我运行这个时,我得到一个错误,说“你有SQL语法附近有错误吗?WHERE Patient_ID =?”

当我使用system.out.println(sql2);

输出sql时

值未在sql2中设置

2 个答案:

答案 0 :(得分:6)

当您准备一个语句时,数据库会构造一个执行计划,如果该表不存在,它就无法执行。换句话说,placehodlers只能用于,而不能用于对象名称或保留字。在这种情况下,您必须依赖Java来构造字符串:

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

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

答案 1 :(得分:0)

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

PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setint(1, key);
ResultSet result = preparedStatement.executeQuery();