使用 PreparedStatement 登录在 Java 中不起作用 [重复]
Posted
技术标签:
【中文标题】使用 PreparedStatement 登录在 Java 中不起作用 [重复]【英文标题】:Login with PreparedStatement is not working in Java [duplicate] 【发布时间】:2020-05-20 06:55:28 【问题描述】:public static void main(String[] args)
Scanner sc = new Scanner(System.in);
System.out.print("Enter username: ");
String un = sc.nextLine();
System.out.print("Enter password: ");
String up = sc.next();
sc.close();
try
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDB",
"root", "pass");
String q = "select * from users where username = ? and password = ?";
PreparedStatement ps = con.prepareStatement(q);
ps.setString(1, un);
ps.setString(2, up);
ResultSet rs = ps.executeQuery(q);
if(rs.next())
System.out.println("Welcome "+un);
else
System.out.println("Invalid username or password");
catch(Exception e)
System.out.println(e.getMessage());
获取输出为:
Enter username: Raja
Enter password: 111
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
为什么会这样?它应该可以工作但显示错误
【问题讨论】:
【参考方案1】:ResultSet rs = ps.executeQuery(q);
您必须使用无参数版本,否则您正在尝试执行字符串的内容,而不是您准备好的语句。
ResultSet rs = ps.executeQuery();
【讨论】:
哦,是的.. 谢谢亲爱的.. 我没有弄错我做错了什么以上是关于使用 PreparedStatement 登录在 Java 中不起作用 [重复]的主要内容,如果未能解决你的问题,请参考以下文章
[Js-JDBC]SQL注入及解决,Statement与PreparedStatement
PreparedStatement可以有效地防止sql被注入