John Joe John Joe - 1 year ago 45
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);



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

Answer Source

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
    (SELECT ? title) mt
    SELECT 1 FROM movie_title WHERE title = ?)