简体   繁体   中英

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. 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. Also according your error message you need to add a white space after from (check fromspmovy_admin)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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