简体   繁体   English

无法在Java应用程序中执行SQL查询

[英]SQL query not executing in java application

I'm using JDBC for the first time and having a tough time at it. 我是第一次使用JDBC,但经历了一段艰难的时期。 This is a code snippet that is giving me error: 这是给我错误的代码片段:

//STEP 4: Execute a query
System.out.println("Creating statement...");
String sql;
sql = "SELECT * FROM user where username=? and password=?";
stmt = conn.prepareStatement(sql);
//Bind values into the parameters.
stmt.setString(1, value1);  // This would set username
stmt.setString(2, value2); // This would set password
ResultSet rs = stmt.executeQuery(sql);

I'm getting the following error in NetBeans: 我在NetBeans中遇到以下错误:

" 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" jdbc.exceptions.jdbc4.MySQLSyntaxErrorException :您的SQL语法有错误;请检查与MySQL服务器版本相对应的手册,以在第1行的' ? and password=? '附近使用正确的语法”

There is a long list after this but I think this is the thing which is causing me problems. 此后有一长串,但我认为这是导致我出现问题的原因。 What am I doing wrong? 我究竟做错了什么?

You already have set the SQL for the statement and the parameters are bound. 您已经为语句设置了SQL ,并且绑定了参数。

Hence, you need not set the SQL again for the same statement. 因此,您无需为同一条语句再次设置SQL Otherwise it is an invalid statement and and exception is thrown. 否则,它是无效的语句,并引发异常。

Change : 变更

ResultSet rs = stmt.executeQuery(sql);

To :

ResultSet rs = stmt.executeQuery();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM