简体   繁体   English

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

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

Hi i have a small problem, how do i switch tables to get results from?? 嗨,我有一个小问题,如何切换表格以获取结果? The code below is not working.However that should give you some idea of what i am trying to do. 下面的代码不起作用。但是,这应该使您对我正在尝试执行的操作有所了解。 Thanks for the help 谢谢您的帮助

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);

The full code: 完整代码:

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();

The error i am getting: 我得到的错误:

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

Answer[SOLVED]: 答案[已解决]:

forgot to put white space 忘了放空格

from " + typelogin + " where

From your error message: 'fromspmovy_admin where ... looks like you missed a whitespace between from and your table name. 从您的错误消息中: 'fromspmovy_admin where ...似乎您错过了from和表名之间的空格。 Make sure you're doing this in the right way in all your methods (note that in your current example this won't happen). 确保在所有方法中都以正确的方式执行此操作(请注意,在当前示例中,这不会发生)。

If you will use ? 如果要使用? for pass the variables, you must use PreparedStatement not Statement. 要传递变量,必须使用PreparedStatement而不是Statement。 Also according your error message you need to add a white space after from (check fromspmovy_admin) 另外根据您的错误消息,您需要在from之后添加一个空格(检查fromspmovy_admin)

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

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