Error in JDBC query - java

sql = "select milk_rate from special_milk_rate
where code_producer_id=? and effective_from <= ?
and effective_till >= ?"
I am getting error in this query when in my JDBC code
Exception: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 effective_from <= ? and effective_till >= ?' at line 1
But when I run it in MySQL command prompt with some values it runs fine there.

ResultSet rst= prest.executeQuery(sql);
This is incorrect. It should be executeQuery().
The sql gets passed to execute when using a Statement. It gets passed to the PreparedStatement instead when using binding variables. Since you are using the Statement API, JDBC is executing it without substituting in your binding variables and wondering what to do with the literal question marks.

You have to use prepared statements instead of "normal" statements to have the question marks replaced by parameters.

Related

Issue with the Prepared Stetement Parameter when injecting Single Parameter in Select Query [duplicate]

This question already has answers here:
MySQLSyntaxErrorException near "?" when trying to execute PreparedStatement
(2 answers)
I am trying a simple query with in parameter with mysql 5.5 through jdbc code
(1 answer)
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax
(2 answers)
Closed 2 years ago.
I am trying to create the prepared statement for the select query
String Select_Query = "select * from customers where customerNumber=? ";
Connection connection = DriverManagersSQL.getDriverMangerInstance();
preparedStatement statement = connection.prepareStatement(Select_Query);
statement.setInt(1, 101);
ResultSet resultSet = statement.executeQuery(Select_Query);
But I am having one error like this :
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
I ran the query into the database and its working fine. There is no syntax error. This happens with me all the time when I try to use with single filtering parameter. Any suggestions will be appreciated.
Thanks
Don't call
statement.executeQuery(Select_Query)
You've already set up your PreparedStatement. It's already got your SQL and the parameters that go in it.
Just call
statement.executeQuery()
instead.
executeQuery() is a method of PreparedStatement that will perform the query you already gave it, using the parameters you have already set.
executeQuery(String) is a method of Statement which tries to execute the query you are giving it now. It does not use your parameters, and the docs specifically say that if you call this method on a PreparedStatement it will cause an SQLException.

SQL Query fails in Java but works outside

I have a simple SQL query. It works fine if I use it in SequelPro but when I try to use the query in a Java statement if fails.
The query is operating on a simple table that only has two fields, idpolari and word. I originally structured the query as SELECT * FROM polari when this did not work I tried naming the specific fields. Have tried executing the query in SequelPro and against the database and it works fine. It also works from the command line. Just not working in Java.
I am working in Netbeans running MySQL on an IMac.
sql = "SELECT idpolari, word FROM polari";
Statement stmt = con.createStatement();
ResultSet res1 = stmt.executeQuery(sql);
I would have expected the full contents fo the polari table, what I get is this error message:
INFO: 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 SELECT idpolari, word FROM polari

Why can't I set a variable in a prepared statement in MySQL?

I'm running a script to insert some data in a MySQL database, and it runs properly in the MySQL workbench. However, when I try to run it from Java via the JDBC, I get an error. The script is:
INSERT INTO `pa_record` (`username`, `pa_record_type`, `record_time`) VALUES (?, ?, CURRENT_TIMESTAMP);
SET #record_id := 1;
INSERT INTO `pa_crud` (`pa_record_id`, `table_name`) VALUES (#record_id, ?);
The error I get from the JDBC is
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 'SET #record_id := 1;
INSERT INTO pa_crud (pa_record_id, table_name) VALUES' at line 2
Any ideas?
Many (most?) database access libraries do not allow multiple statements in a single execute; those that do, usually need to have the feature activated with a setting change. It's likely not complaining about the SET, but that you had anything after the end of the first query at all.

Update command with special SQL keywords in JDBC

I am trying a update an entry in my SQL table which has a column name "from" in JDBC.
Following is the SQL command that I am trying to execute:
sql = "Update email_template set [from]="+"'"+3+"'"+" WHERE id="+idno;
stmt.executeUpdate(sql);
However it shows the following error:
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 '[from]='Akshit' WHERE id=1' at line
MySQL's way of escaping column names is by using backticks:
sql = "Update email_template set `from`="+"'"+3+"'"+" WHERE id="+idno;
I recommend using java.sql.PreparedStatement when handling SQL in Java. It can be used for batches and ensures malicious SQL is not injected as part of the SQL code.
This is how your code looks with a PreparedStatement:
PreparedStatement stmt = connection.prepareStatement("UPDATE `email_template` SET `from` = ? WHERE id = ?");
stmt.setInt(1, 3);
stmt.setInt(2, idno);
stmt.executeUpdate();
If this is an operation you execute for many rows in one go, replace stmt.executeUpdate() with stmt.addBatch() (likely in some loop) and when you're ready to execute the batched updates you call stmt.executeBatch().
Note that both executeUpdate() and executeBatch() return how many rows were affected; which is something you may want to validate after a commit.

SQL query works in phpmyadmin but not when using jdbc and java

This query works when I input it through phpmyadmin.
INSERT INTO conversation (user_id) VALUES (?);
INSERT INTO conversation (conversation_id, user_id)
VALUES ((SELECT LAST_INSERT_ID()), ?)
However when I send that query using jdbc and java I get an error -
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 'INSERT INTO conversation (conversation_id, user_id) VALUES ((SELECT LAST_INSERT_' at line 1"
I am using the exact same query. I checked by calling toString on the PreparedStatement and copying and pasting it into phpmyadmin and executing it and it worked fine. It just doesn't work through java. Any ideas whats wrong?
By default, you cannot execute multiple statements in one query through JDBC. Splitting it into two calls will work, as will changing the allowMultiQueries configuration property to True.
JDBC Configuration Properties — allowMultiQueries:
Allow the use of ';' to delimit multiple queries during one statement (true/false), defaults to 'false', and does not affect the addBatch() and executeBatch() methods, which instead rely on rewriteBatchStatements.
Default value: false

Categories

Resources