[英]How to insert in two tables in one time? prepared statements
如何一次插入两个表?
我需要插入第二个表user_information
字段user_id
与第一个表user
插入返回id
,我找到了这个答案,但我找不到如何使用 params 准备语句
var dbQuery = 'WITH insertUser AS (
INSERT INTO "user" (status, create_date) VALUES ($1, $2) RETURNING id
)
, insertUserInformation AS (
INSERT INTO user_information (user_id, email) VALUES ($3, $4)
)
';
yield queryPromise(dbClient, dbQuery, [status, timestamp, ??, email]);
在 postgresql 中这是不可能的。 我通过创建函数并简单地使用参数执行来解决完全相同的问题。 正如我在你的表结构中看到的,你没有很多属性,所以这会相对容易。
示例代码:
function.sql
CREATE OR REPLACE FUNCTION createSomething
(
IN attr1 VARCHAR(20),
IN attr2 VARCHAR(200)
)
RETURNS void AS $$
DECLARE userId INTEGER;
BEGIN
INSERT INTO table1 (col1, col2) VALUES
(
attr1,
attr2
) RETURNING id INTO userId;
INSERT INTO table2 (user_id, col11, col2) VALUES
(
userId,
col11,
col12
);
END;
$$ LANGUAGE plpgsql;
用法:
SELECT createSomething('value1', 'value2');
请注意,第二个插入语句将知道最近用户的 id 是什么并将使用它。
使用事务。 这样,要么提交所有查询,要么不提交任何查询。 并且在您执行所有查询之前的不完整状态对于其他进程是不可见的。
有关如何在node-postgres
进行交易的更多信息,请访问https://github.com/brianc/node-postgres/wiki/Transactions
作为参考,最相关的部分是:
var Client = require('pg').Client;
var client = new Client(/*your connection info goes here*/);
client.connect();
var rollback = function(client) {
//terminating a client connection will
//automatically rollback any uncommitted transactions
//so while it's not technically mandatory to call
//ROLLBACK it is cleaner and more correct
client.query('ROLLBACK', function() {
client.end();
});
};
client.query('BEGIN', function(err, result) {
if(err) return rollback(client);
client.query('INSERT INTO account(money) VALUES(100) WHERE id = $1', [1], function(err, result) {
if(err) return rollback(client);
client.query('INSERT INTO account(money) VALUES(-100) WHERE id = $1', [2], function(err, result) {
if(err) return rollback(client);
//disconnect after successful commit
client.query('COMMIT', client.end.bind(client));
});
});
});
PostgreSQL Prepared Statements 不会让你这样做。 您将不得不使用事务。
以下是使用 ES7 语法使用pg-promise实现的示例:
const pgp = require('pg-promise')({
// initialization options;
});
const db = pgp(/* your connection object or string */);
db.tx(async t => {
const user = await t.one('INSERT INTO user(status, create_date) VALUES($1, $2) RETURNING id', [status, timestamp]);
return t.none('INSERT INTO user_information(user_id, email) VALUES($1, $2)', [user.id, email]);
})
.then(() => {
// SUCCESS;
})
.catch(error => {
// ERROR;
});
我不相信这可以作为一个自然的 sql 语句来完成。 你必须把它包装成一个过程或其他一些机制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.