尝试将数据插入MySQL时出错

时间:2016-05-12 15:25:59

标签: java mysql jdbc

我使用下面的代码在数据插入MySQL之前进行检查。但是,我收到错误如下

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)

这是我的代码

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(); 

    }   

被修改

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

1 个答案:

答案 0 :(得分:4)

当您使用VALUES关键字时,不能在SQL中放置WHERE子句。尝试这样的事情:

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

我主要使用SQL Server,因此我不确定它是否对MySQL完全有效,但它会是类似的。

好的,对于MySQL来说,它必须有所不同:

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