[英]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.