繁体   English   中英

如何在PreparedStatement中更改from子句的表名

[英]How to change table name of from clause in PreparedStatement

嗨,我有一个小问题,如何切换表格以获取结果? 下面的代码不起作用。但是,这应该使您对我正在尝试执行的操作有所了解。 谢谢您的帮助

String typelogin=null;
if(xx){
   typelogin="users_table";
}else{
   typelogin="admin_table";
}
String sqlStr = "Select * from "+typelogin+" where username=? and userpassword=?";
PreparedStatement stmt = conn.prepareStatement(sqlStr);

完整代码:

Statement stmt = conn.createStatement();

            String sqlStr = "Select * from "+typelogin+" where username=? and userpassword=?";


            PreparedStatement pstmt=conn.prepareStatement(sqlStr);
            pstmt.setString(1,user);
            pstmt.setString(2,password);
            //step 6 Process result
            ResultSet rs = pstmt.executeQuery();

我得到的错误:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'fromspmovy_admin where username='abc' and userpassword='abc'' at line 1

答案[已解决]:

忘了放空格

from " + typelogin + " where

从您的错误消息中: 'fromspmovy_admin where ...似乎您错过了from和表名之间的空格。 确保在所有方法中都以正确的方式执行此操作(请注意,在当前示例中,这不会发生)。

如果要使用? 要传递变量,必须使用PreparedStatement而不是Statement。 另外根据您的错误消息,您需要在from之后添加一个空格(检查fromspmovy_admin)

暂无
暂无

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

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