简体   繁体   English

MySQL Java PreparedStatement插入(如果不存在)

[英]mysql java preparedstatement insert if not exist

i try to fill data into my databse. 我尝试将数据填充到我的数据库中。 But i don't want dublicates based on the time. 但我不希望根据时间进行重复。 I don't care about the dublicates, because i don't lose any data. 我不在乎复制,因为我不会丢失任何数据。 After a long search i finally found, that you can't use WHERE NOT EXIST with an INSERT INTO . 经过长时间的搜索,我终于发现,您不能在INSERT INTO使用WHERE NOT EXIST

But now i got the next problem. 但是现在我遇到了下一个问题。 I tried these two approaches but none of these works. 我尝试了这两种方法,但是这些方法都没有。

      /*
      preparedStatement = connect.prepareStatement("IF NOT EXISTS(SELECT * FROM gpsdata.data where time=?) "
            + "Begin "
            + "INSERT INTO gpsdata.data VALUES (default, ?, ? , ?, ?, ?, ?, ?, ?) "+
              "END");
      */
      preparedStatement = connect.prepareStatement("INSERT INTO gpsdata.data VALUES (default, ?, ? , ?, ?, ?, ?, ?, ?) "
            + "SELECT ? FROM gpsdata.data WHERE NOT EXISTS(SELECT * FROM gpsdata.data where time = ?)");

Both gave me some mysql syntax errors. 两者都给了我一些mysql语法错误。 I can't figure out what is wrong. 我不知道怎么了。 I am new to mysql. 我是mysql新手。 The last try gave me at least a different error: 最后一次尝试给了我至少一个不同的错误:

MySQLSyntaxErrorException: You have an error in your SQL syntax; MySQLSyntaxErrorException:您的SQL语法有错误; check the manual... ... to use near 'SELECT 1448982118099 WHERE NOT EXISTS(SELECT * FROM gpsdata.data where time =14') at line 1 检查手册... ...在第1行的'SELECT 1448982118099 WHERE NOT EXISTS(SELECT * FROM gpsdata.data where time = 14')附近使用

Before the check for dublicates, the code was running fine. 在检查是否有重复项之前,代码运行良好。 So it should be the new statement. 因此,这应该是新的声明。

Regards, Eric 问候,埃里克

EDIT: I don't want to copy my data into an other table. 编辑:我不想将我的数据复制到另一个表。

? is not a valid parameter in SELECT ? SELECT ?不是有效参数SELECT ? . You have to literally name a column. 您必须从字面上命名一列。

In order to connect insert with parameters part with condition part you can use select from dual . 为了将带有参数部分的插入件与 条件部分连接起来可以使用double选择 I have tried the statement below with Oracle. 我已经尝试过使用Oracle进行以下声明。

preparedStatement = connect.prepareStatement("INSERT INTO gpsdata.data select 'default', ?, ? , ?, ?, ?, ?, ?, ? from dual
            WHERE NOT EXISTS(SELECT * FROM gpsdata.data where time = ?)");

ps: please be aware that you use time variable twice. ps:请注意,您两次使用了时间变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM