简体   繁体   English

仅在行不存在时插入

[英]Insert only if row doesn't exist

I am using PreparedStatement to prepare sql queries. 我正在使用PreparedStatement来准备SQL查询。 I want to insert a row in table if and only if it doesn't exist. 当且仅当它不存在时,我想在表中插入一行。

I tried this - 我试过这个 -

INSERT INTO users (userId) VALUES (?) ON DUPLICATE KEY UPDATE userId = ?

But this will unnecessarily update the userId. 但这将不必要地更新userId。

How can i insert the userId here ? 我如何在这里插入userId

INSERT  INTO users 
        (userId) 
SELECT  ?
WHERE   NOT EXISTS
        (
        SELECT  * 
        FROM    users 
        where   userId = ?
        )

You may use 你可以用

 INSERT IGNORE INTO users (userId) VALUES (?) 

But you should understand why do you want ignore errors. 但你应该明白为什么要忽略错误。

on duplicate key does not work correctly when the table is an innodb. 当表是innodb时,复制键无法正常工作。 It creates exactly the problem you are describing. 它创建了您正在描述的问题。 If you need the functionality of an innodb, then should you first check the existence of the row, otherwise can you convert the table to a myisam table. 如果你需要innodb的功能,那么你应该首先检查行的存在,否则你可以将表转换为myisam表。

edit: if you need to check the existence of the row before the decision to insert or update, then would I advice you to use a stored procedure. 编辑:如果您需要在决定插入或更新之前检查行的存在,那么我建议您使用存储过程。

DELIMITER //
CREATE PROCEDURE adjustusers(IN pId int)
BEGIN
DECLARE userid int;
  select  count(id) into userid from users where id = pId;
  if userid = 1 then
   update users set id = pId where id = pId;
  else
   insert into users(id) values(pId);
  end if;
END //
DELIMITER ; 

A stored procedure is precompiled, just as a prepared statement. 存储过程是预编译的,就像准备好的语句一样。 Hence no SQL injection problems and some more functionality and only one call to the database. 因此没有SQL注入问题和一些更多功能,只有一次调用数据库。

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

相关问题 在MySQL中,如何仅在行不存在时插入,仅在现有版本较少时才更新 - In MySQL, how do I insert only when row doesn't exist and update only when existing version is less 如何仅在mysql中不存在的情况下插入值? - how to insert value in mysql only if it already doesn't exist? 我正在尝试仅将新记录插入数据库(如果该记录尚不存在但无法正常工作) - I am trying to only insert a new record into the database if that record doesn't already exist but it isn't working 仅当对象不存在时,DynamoDBMapper才会保存 - DynamoDBMapper save only if object doesn't exist 仅在不存在的字符串中添加一个字符串 - Add a string to a file ONLY if it doesn't exist JDBCTemplate:如果ID不存在,则更新或插入 - JDBCTemplate : either Update or Insert if ID doesn't exist MongoDB:如果不存在则插入记录,如果存在则忽略 - MongoDB: insert record if it doesn't exist, ignore if it does Java:如果ArrayList中不存在值,则删除mysql行 - Java: Delete mysql row if value doesn't exist in ArrayList Kafka:仅在尚不存在时发布消息 - Kafka: Publish message only if it doesn't already exist Android SQLite 仅在数据不存在时添加记录 - Android SQLite adding a record only if data doesn't exist
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM