在学习PreparedStatement 打出代码后运行老是出错 请问代码哪里出问题了
代码如下
package mybatisTry3.mts_soft.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Test2a {
public static void main(String[] args) throws ClassNotFoundException {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql:///mybatis2";
String user = "root";
String pwd = "root";
Connection conn = DriverManager.getConnection(url, user, pwd);
Test2a test = new Test2a();
String name = "张三";
String password = "123";
boolean flag = test.login(name, password, conn);
if(flag) {
System.out.println("登录成功");
}else {
System.out.println("登录失败");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public boolean login(String name, String password, Connection conn) throws SQLException {
String sql = "select * from student where name = ? and password = ?";
PreparedStatement pstmt;
ResultSet rs;
boolean flag = false;
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setString(2, password);
rs = pstmt.executeQuery(sql);
while(rs.next()) {
flag = true;
}
rs.close();
pstmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flag;
}
}
报错信息如下
java.sql.SQLSyntaxErrorException: 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
at mysql.connector.j@8.2.0/com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:121)
at mysql.connector.j@8.2.0/com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at mysql.connector.j@8.2.0/com.mysql.cj.jdbc.StatementImpl.executeQuery(StatementImpl.java:1201)
at mybatisTry3/mybatisTry3.mts_soft.test.Test2a.login(Test2a.java:46)
at mybatisTry3/mybatisTry3.mts_soft.test.Test2a.main(Test2a.java:22)
登录失败
问题出在你在执行PreparedStatement的executeQuery方法时传入了sql字符串。这个方法不需要传入参数,因为预编译的sql已经在prepareStatement方法中指定了。所以在这里你应该把executeQuery(sql)改成executeQuery()就可以了。
修改后的代码如下:
public boolean login(String name, String password, Connection conn) throws SQLException {
String sql = "select * from student where name = ? and password = ?";
PreparedStatement pstmt;
ResultSet rs;
boolean flag = false;
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setString(2, password);
rs = pstmt.executeQuery();
while (rs.next()) {
flag = true;
}
rs.close();
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
希望能帮到你!
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 FishC 发表于 2024-1-3 18:52
问题出在你在执行PreparedStatement的executeQuery方法时传入了sql字符串。这个方法不需要传入参数,因为预 ...
谢谢小助理 mumei2018 发表于 2024-01-03 18:53
谢谢小助理
不客气,如果你还有其他问题,随时来问我哦!祝你编程学习顺利!
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
页:
[1]