我试图在“已投票”一栏中使用JDBC读取MySQL的值。该语法应该搜索另一个名为“Username”的列(它是主键并且是唯一的)并返回“has voted”的相应值。 这是错误代码所遵循的方法的代码。
boolean hasVoted(int userid){
String q = "SELECT has_voted from voters"+
"WHERE Username ="+ "'" + userid +"'";
try{
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo","abhi", "abhi");
Statement s = conn.createStatement();
ResultSet r = s.executeQuery(q);
if(r.next()){
int b = r.getInt("has_voted");
if(b==0){
return(false);
}
else{
return(true);
}
}
return(false);
}
catch(Exception e){
e.printStackTrace();
return(false);
}
}
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 '='2'' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:377)
at com.mysql.jdbc.Util.getInstance(Util.java:360)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:978)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3887)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3823)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2435)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2582)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2526)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2484)
at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1446)
at DistrictDatabase.hasVoted(DistrictDatabase.java:242)
at DistrictDatabase.initDatabase(DistrictDatabase.java:64)
at Server.main(Server.java:46)
答案 0 :(得分:0)
在选民之间增加空间" &安培; "其中"像这样
String q = "SELECT has_voted from voters"+
" WHERE Username ="+ "'" + userid +"' ;";