简体   繁体   中英

Problems with prepareStatement for variable table name

I have a problem with prepareStatement in my project
The problem is that i want to query tables according to the type of user ie if user is general then access userlist table and if user is administrator then access admin table
I have tried like :

String userid=request.getParameter("userid");
String pwd=request.getParameter("pwd");
String check = request.getParameter("radio");
String table;
String status="";
if(check.equals("General"))
table="userlist";
else
table="Administrator";
try{
String sql = "Select status from"+table+"where userid=? and pwd=?";
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost/Quiz?","root","password");
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1,userid);
ps.setString(2,pwd);
ResultSet rs=ps.executeQuery();

I get following exception :

Errorcom.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 'userid='nawed13593' and pwd='hello'' at line 1

I dont want to use createStatement because that will make my project prone to sql injection
Can anyone please help me solve this and the reason why the above exception was thrown? Thank you in advance

You don't have any spaces before or after your table name. You will wind up with this, in the "Administrator" case:

Select status fromAdministratorwhere userid=? and pwd=?

Insert spaces into your SQL statement string:

//                              v         v
String sql = "Select status from "+table+" where userid=? and pwd=?";

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