POSTGRESQL INSERT如果特定的行名不存在! [英] POSTGRESQL INSERT if specific row name don't exists !
本文介绍了POSTGRESQL INSERT如果特定的行名不存在!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
只有当我的模型不存在时,我才试图在Postgresql数据库中进行INSERT。我使用PDO连接,我尝试使用IGNORE和ON DUPLICATE KEY UPDATE,但是在PDO /语法中出现错误。
I'm trying to INSERT in my Postgresql database only if my model don't exists. I'm using PDO connection, I try IGNORE and ON DUPLICATE KEY UPDATE but with errors in PDO / syntax.
我的代码: p>
MY Code:
if(isset($_POST['insertModel'])){
require("includes/connection.php");
$models = $_POST['name'];
$parametros = array($models);
$sth = $dbh->prepare("INSERT INTO models (name) VALUES ( ? )");
$sth->execute($parametros);
if($sth){
header("location: admin.php?model_inserted=1");
}
}
谢谢
推荐答案
ON DUPLICATE KEY UPDATE
是MySQL语法,而不是PostgreSQL。 PostgreSQL没有简单的SQL语法来做你想要的。
ON DUPLICATE KEY UPDATE
is MySQL syntax, not PostgreSQL. PostgreSQL doesn't have a simple SQL syntax to do what you want.
但是文档包含执行此功能的函数的示例代码。
But the documentation includes example code for a function that does that.
CREATE TABLE db (a INT PRIMARY KEY, b TEXT);
CREATE FUNCTION merge_db(key INT, data TEXT) RETURNS VOID AS
$$
BEGIN
LOOP
-- first try to update the key
UPDATE db SET b = data WHERE a = key;
IF found THEN
RETURN;
END IF;
-- not there, so try to insert the key
-- if someone else inserts the same key concurrently,
-- we could get a unique-key failure
BEGIN
INSERT INTO db(a,b) VALUES (key, data);
RETURN;
EXCEPTION WHEN unique_violation THEN
-- do nothing, and loop to try the UPDATE again
END;
END LOOP;
END;
$$
LANGUAGE plpgsql;
这篇关于POSTGRESQL INSERT如果特定的行名不存在!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文