John Joe John Joe - 6 months ago 9
SQL Question

Get error when trying to insert data into MySQL

I'm using below code to do checking before data get inserted into MySQL. However, I get error as below

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 'WHERE NOT EXISTS (SELECT * FROM movie_title WHERE title = 'ABC')' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)


Here my code

public void checkAndAdd(String movieTitle) throws Exception {
// TODO Auto-generated method stub
DatabaseConnection db=new DatabaseConnection();
Connection connect=db.getConnection();
String sql="INSERT INTO movie_title(title) VALUES (?) WHERE NOT EXISTS (SELECT * FROM movie_title WHERE title = ?)";
PreparedStatement ps=connect.prepareStatement(sql);
ps.setString(1,movieTitle);
ps.setString(2,movieTitle);
ps.executeUpdate();
connect.close();
ps.close();

}


Edited

String sql=" IF NOT EXISTS(SELECT * FROM movie_title WHERE title = ?) INSERT INTO movie_title (title) VALUES (?) ";

Answer

You can't put a WHERE clause in your SQL when you're using the VALUES keyword. Try something like this:

IF NOT EXISTS(SELECT 1 FROM movie_title WHERE title = ?)
    INSERT INTO movie_title (title)
    VALUES (?)

I work with SQL Server mostly, so I'm not sure if that's completely valid for MySQL, but it will be something similar.

Okay, for MySQL it has to be a little different:

INSERT INTO movie_title (title)
SELECT mt.title
FROM
    (SELECT ? title) mt
WHERE NOT EXISTS (
    SELECT 1 FROM movie_title WHERE title = ?)