Java SQL语法中的MySQLSyntaxErrorException
我试图使用prepared语句从表中选择数据。但似乎我得到的语法错误,我无法单独解决Java SQL语法中的MySQLSyntaxErrorException,java,mysql,jsp,mysql-connector,Java,Mysql,Jsp,Mysql Connector,我试图使用prepared语句从表中选择数据。但似乎我得到的语法错误,我无法单独解决 try { Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/mydb"; String dbusername = "root"; String dbpassword = ""; // Change it to your Passwo
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mydb";
String dbusername = "root";
String dbpassword = ""; // Change it to your Password
// Setup the connection with the DB
connection = DriverManager.getConnection(url, dbusername,
dbpassword);
String query = "SELECT * FROM admin WHERE username = ? AND password = ?";
try {
// connection.setAutoCommit(false);
selectUser = connection.prepareStatement(query);
selectUser.setString(1, username);
selectUser.setString(2, password);
// Execute preparedstatement
ResultSet rs = selectUser.executeQuery(query);
// Output user details and query
System.out.println("Your user name is " + username);
System.out.println("Your password is " + password);
System.out.println("Query: " + query);
boolean more = rs.next();
// if user does not exist set the validity variable to true
if (!more) {
System.out
.println("Sorry, you are not a registered user! Please sign up first!");
user.setValid(false);
}
// if user exists set the validity variable to true
else if (more) {
String name = rs.getString("name");
System.out.println("Welcome " + name);
user.setName(name);
user.setValid(true);
}
} catch (Exception e) {
System.out.println("Prepared Statement Error! " + e);
}
} catch (Exception e) {
System.out.println("Log in failed: An exception has occured! " + e);
} finally {
}
if (connection != null) {
try {
connection.close();
} catch (Exception e) {
System.out.println("Connection closing exception occured! ");
}
connection = null;
}
return user;
}
我得到以下错误
Prepared Statement Error! 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 '? AND password = ?' at line 1
但是我在代码行中没有看到任何错误。您要做的就是使用这个 改变 到
当您已经在
connection.prepareStatement(查询)中准备好语句时
那么为什么要在selectUser.executeQuery(查询)中再次传递查询代码>您已经在此处准备的语句中加载了查询
selectUser = connection.prepareStatement(query);
因此,通过
ResultSet rs = selectUser.executeQuery();
还读到,
谢谢!我不知道那件事。删除查询参数保存了我的一天。
ResultSet rs = selectUser.executeQuery();
selectUser = connection.prepareStatement(query);
ResultSet rs = selectUser.executeQuery();