Prepared statements with MySQL? - java

I am having some trouble with, what I believe to by syntax, for prepared statements.
I have the following code
String query2="SELECT lname FROM school_student WHERE sid = ? ORDER BY sid;";
PreparedStatement ps = cn.prepareStatement(query2);
ps.setInt(1, 3);
ResultSet rs = ps.executeQuery(query2);
The problem I am having is that I am getting this error message:
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 '? ORDER BY sid' at line 1
However, when I substitute the "?" in my query for a 3, the query works fine with no error and gives me what I want. There seems to be something wrong with how I am setting the value of the "?" in my query? Am I using the wrong syntax?

Simply use
ps.executeQuery();
(i.e. use the overloaded executeQuery() method which doesn't take any argument). You already passed the query when preparing the statement.

use this query :-
String query2 = "SELECT lname FROM school_student WHERE sid =
"+attribute+" ORDER BY sid;";
and simply use
ps.executeQuery();

I think their is syntax problem while preparing query
try this one...
String query2="SELECT lname FROM school_student WHERE sid = +variablename+ ORDER BY sid;"

Related

java.sql.SQLSyntaxErrorException when inserting into MySQL database using PreparedStatement [duplicate]

I'm trying to execute a query using a PreparedStatement in Java.
I am getting error number 1064 when I try to execute my query (syntax error).
I have tested this in MySQL query browser with substituted values which works fine.
What's wrong with my code?
Here's the relevant code:
String query = "select MemberID, MemberName from members where MemberID = ? or MemberName = ?";
Connection conn = DriverManager.getConnection(DATABASE_URL, USERNAME, PASSWORD);
PreparedStatement s = conn.prepareStatement(query);
s.setInt(1, 2);
s.setString(2, "zen");
ResultSet rs = s.executeQuery(query);
Here's the exception I'm getting:
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 '? or MemberName
= ?' at line 1
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 '? or MemberName = ?' at line 1
MySQL doesn't understand the meaning of ? in the SQL query. It's indeed invalid SQL syntax. So somehow it's not been replaced by PreparedStatement. And guess what?
PreparedStatement s = conn.prepareStatement(query);
s.setInt(1, intValue);
s.setString(2, strValue);
rs = s.executeQuery(query); // Fail!
You're overridding the prepared query with the original query! You need to call the argumentless PreparedStatement#executeQuery() method instead of Statement#executeQuery(String).
PreparedStatement s = conn.prepareStatement(query);
s.setInt(1, intValue);
s.setString(2, strValue);
rs = s.executeQuery(); // OK!
Unrelated to the problem, your code is leaking resources. The DB will run out of them after several hours and your application will crash. To fix this, you need to follow the JDBC idiom of closing Connection, Statement and ResultSet in the finally block of the try block where they're been acquired. Check the JDBC basic tutorial for more detail.
If you look at the javadocs for Statement (the superclass of PreparedStatement), the method docs for executeQuery(String) and executeUpdate(String) say this:
Note: This method cannot be called on a PreparedStatement or CallableStatement.
That's what you are doing here: calling executeQuery(String) from Statement on a PreparedStatement object.
Now since the javadocs say that you "cannot" do this, actual behavior you get is unspecified ... and probably JDBC driver dependent. In this case, it appears that the MySQL driver you are using is interpreting this to mean that you are doing the update as a non-prepared statement, so that the ? tokens are NOT interpreted as parameter placeholder. That leads the server-side SQL parser to say "syntax error".
(It would be easier for programmers if a different unchecked exception was thrown by the MySQL driver if you did this; for example UnsupportedOperationException. However, the standard JDBC javadocs don't say what should happen in this situation. It is up to the vendor what their drivers will do.)

Strange behaviour of Java PreparedStatement

I have the following code
try{
sql = "Select Time, Text WHERE Sender =?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, "ABC");
rs = stmt.executeQuery();
}catch(SQLException){
System.out.println(e.getMessage());
}
And get the following error:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE Sender ='ABC'' at line 1
There is an extra ' in my SQL query, how can I fix that?
It's not the "extra" ' that's the issue. You actually need that for your DB to understand the text you're providing.
The issue is that you're issuing a SELECT statement that is requesting fields from a table which you have not specified. You need to add the table name:
Select Time, Text FROM <tablename here> WHERE Sender =?
Edit: Apparently MariaDB doesn't consider time and text as reserved words as #Andreas pointed out in a comment on this answer.

SQL query : Wrong syntax

I'm tring to write a query but I obtain a syntax error. I know that this error is in the query's syntax. This is the query
ResultSet set=statement.executeQuery("Select * from Ombrellone where PosizioneX='"+c.getX()+"',PosizioneY='"+c.getY()+"'" );
Anyone can help me?
If you want to have multiple conditions on select, you must use AND, not comma.
ResultSet set=statement.executeQuery("Select * from Ombrellone where PosizioneX='"+c.getX()+"' and PosizioneY='"+c.getY()+"'" );
Side note : Avoid using String concatination with query parameters. They causes SQL injections and try using PreparedStatement.
Though the problem in your case was basically because you used comma on your SQL query which is wrong you can use AND or OR for condition fulfillment when using WHERE clause but also
I would suggest you to use PreparedStatement over Statement.
String query = "Select * from Ombrellone where PosizioneX = ? and PosizioneY = ?"
PreparedStatement statement = conn.prepareStatement(query);
statement.setString(1,c.getX());
statement.setString(2,c.getY());
ResultSet resultSet = statement.executeQuery();
Refer difference between statement and preparedstatement

PreparedStatement and LIKE error

I'm programming a simple app in java se with jdk 1.7, using netbeans 7.1.2 and MySQL 5.
But i have an error in the next code:
String sql = "SELECT idpaciente, ap_paterno, ap_materno, nombres, edad, direccion, telefono, descuento, movil, email, docId FROM paciente WHERE ap_paterno LIKE ? ";
pst = con.prepareStatement(sql);
pst.setString(1, paciente.getApellidoPaterno());
ResultSet rs = pst.executeQuery(sql);
This code compiling good, but after execute,i have an error of syntax, netbeans says:
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 '?' at line 1
Using debugger of netbeans, the error is in executeQuery, but i can not find my error.
PreparedStatement.executeQuery() does not take any argument, however since the interface inherits Statement.executeQuery(String sql) you are calling that instead. Just call:
ResultSet rs = pst.executeQuery();
http://www.theserverside.com/discussions/thread.tss?thread_id=33182
The above link has some discussion on this topic. Apparently preprared statements don't work for 'like' and 'in'.
So the problem is that the prepared statement fails to substitute the ? and the resulting query is not correct. The error you see comes straight from mysql.

MySQLSyntaxErrorException near "?" when trying to execute PreparedStatement

I'm trying to execute a query using a PreparedStatement in Java.
I am getting error number 1064 when I try to execute my query (syntax error).
I have tested this in MySQL query browser with substituted values which works fine.
What's wrong with my code?
Here's the relevant code:
String query = "select MemberID, MemberName from members where MemberID = ? or MemberName = ?";
Connection conn = DriverManager.getConnection(DATABASE_URL, USERNAME, PASSWORD);
PreparedStatement s = conn.prepareStatement(query);
s.setInt(1, 2);
s.setString(2, "zen");
ResultSet rs = s.executeQuery(query);
Here's the exception I'm getting:
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 '? or MemberName
= ?' at line 1
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 '? or MemberName = ?' at line 1
MySQL doesn't understand the meaning of ? in the SQL query. It's indeed invalid SQL syntax. So somehow it's not been replaced by PreparedStatement. And guess what?
PreparedStatement s = conn.prepareStatement(query);
s.setInt(1, intValue);
s.setString(2, strValue);
rs = s.executeQuery(query); // Fail!
You're overridding the prepared query with the original query! You need to call the argumentless PreparedStatement#executeQuery() method instead of Statement#executeQuery(String).
PreparedStatement s = conn.prepareStatement(query);
s.setInt(1, intValue);
s.setString(2, strValue);
rs = s.executeQuery(); // OK!
Unrelated to the problem, your code is leaking resources. The DB will run out of them after several hours and your application will crash. To fix this, you need to follow the JDBC idiom of closing Connection, Statement and ResultSet in the finally block of the try block where they're been acquired. Check the JDBC basic tutorial for more detail.
If you look at the javadocs for Statement (the superclass of PreparedStatement), the method docs for executeQuery(String) and executeUpdate(String) say this:
Note: This method cannot be called on a PreparedStatement or CallableStatement.
That's what you are doing here: calling executeQuery(String) from Statement on a PreparedStatement object.
Now since the javadocs say that you "cannot" do this, actual behavior you get is unspecified ... and probably JDBC driver dependent. In this case, it appears that the MySQL driver you are using is interpreting this to mean that you are doing the update as a non-prepared statement, so that the ? tokens are NOT interpreted as parameter placeholder. That leads the server-side SQL parser to say "syntax error".
(It would be easier for programmers if a different unchecked exception was thrown by the MySQL driver if you did this; for example UnsupportedOperationException. However, the standard JDBC javadocs don't say what should happen in this situation. It is up to the vendor what their drivers will do.)

Categories