gpt4 book ai didi

mysql - sql 准备语句 : INSERT INTO if not exist

转载 作者:行者123 更新时间:2023-11-28 23:22:05 24 4
gpt4 key购买 nike

只有当我的数据库中不存在数据时,我才尝试使用 preparedStatement 插入数据,但出现错误。

#1064 - Erreur de syntaxe près de 'INTO `test` (`id_test`, `name`) VALUES ("1", "TEST")' à la ligne 1

代码:

SET @preparedStatement = INSERT INTO `test` (`id_test`, `name`) VALUES ("1", "TEST");
PREPARE alterIfNotExists FROM @preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;

德兹

最佳答案

首先,SQL语句PREPARE/EXECUTE在MySQL和PostgreSQL中有不同的语法。它们不兼容。

MySQL:

SET @preparedStatement =
'INSERT INTO test (id_test, name, other) VALUES (''1'', ''TEST'', ?)';
PREPARE alterIfNotExists FROM @preparedStatement;
SET @other = 'STRING'
EXECUTE alterIfNotExists USING @other;
DEALLOCATE PREPARE alterIfNotExists;

PostgreSQL:

PREPARE alterIfNotExists(text) AS 
INSERT INTO test (id_test, name, other) VALUES ('1', 'TEST', $1);
EXECUTE alterIfNotExists('STRING');
DEALLOCATE PREPARE alterIfNotExists;

每种语言都有用于参数化查询的 API,这些 API 将更有可能在 MySQL 和 PostgreSQL 之间兼容。例如,在带有 PDO 的 PHP 中,两个数据库(和其他数据库)的用法相同:

<?php

$stmt = $pdo->prepare(
"INSERT INTO test (id_test, name, other) VALUES ('1', 'TEST', ?)");
$stmt->execute(["STRING"]);

对于您问题的另一部分,如果数据已经存在则避免插入,这在 MySQL 和 PostgreSQL 之间的处理方式也不同。

MySQL:

INSERT IGNORE INTO ...

如果插入会导致任何类型的错误,这将跳过插入。

或者,如果某行的值位于唯一键列中,您可以将某行更改为当前值。

INSERT INTO test (id_test, name, other) VALUES ('1', 'TEST', ?)
ON DUPLICATE KEY UPDATE name=VALUES(name), other=VALUES(other);

PostgreSQL:

INSERT INTO test (id_test, name, other) VALUES ('1', 'TEST', ?)
ON CONFLICT DO NOTHING;

或:

INSERT INTO test (id_test, name, other) VALUES ('1', 'TEST', ?)
ON CONFLICT DO UPDATE SET ...

参见 https://www.postgresql.org/docs/current/static/sql-insert.html#SQL-ON-CONFLICT

关于mysql - sql 准备语句 : INSERT INTO if not exist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41139277/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com