我可以通过哪种方式从Python脚本执行psql命令?我的代码从PostgreSQL数据库插入和更新数据(使用psycopg2和cursor方法)。当我执行像
这样的查询时,它工作正常cursor.execute("UPDATE Segment set idcurve = %s where id = %s ", (id_curve, id_segment,))
但是在psql情况下,当我将命令传递给cursor.execute
(see edits to similar question)时,我会得到SyntaxError: syntax error at or near "\"
。此外,该命令在console.sql DataGRIP中失败(无论如何,它将对所有行执行...)
此命令仅在外壳程序中有效吗(我必须使用os.system吗?因为cursor
无法解释?
编辑尝试子过程:
import subprocess
sql = """SELECT uuid IS NULL AS is_uuid FROM dpoint WHERE uuid = '5547f4b7-00b3-4aac-8ceb-c9ca163a0214';
\gset
\if :is_uuid
INSERT INTO DPoint (uuid) VALUES ('5547f4b7-00b3-4aac-8ceb-c9ca163a0214');
WITH ins1 AS (INSERT INTO Point (latitude, longitude, srid)
VALUES (64.44, 28.77, 4326) RETURNING id AS id_point)
INSERT INTO SPoint (idPoint, uuiddpt) VALUES ((SELECT id_point FROM ins1), '5547f4b7-00b3-4aac-8ceb-c9ca163a0214');
\endif
"""
subprocess.check_call(['psql -h localhost -d dbase -U myuser -W --command={}'.format(sql)], env={'PGPASSWORD': 'mypass'})
投掷OSError: [Errno 36] File name too long
EDIT2
subprocess.check_call(['psql', '-q', '-U', 'myuser', '-h', 'localhost', '-c', '{}'.format(sql), 'dbase'], env={'PGPASSWORD': 'mypass'})
当我拆分所有参数时,查询将尝试执行->它以syntax error at or near "\"
失败。 -E
(如卢梅建议)无济于事。如果我将查询保存到.sql文件,但是我希望以交互方式执行它,则它可以工作。
EDIT3
根据--command = command一章中的psql tutorial,有两种方法可用于混合SQL和psql元命令。有什么可能将其包装在子流程中?我都尝试过,但是出现了多余的反斜杠,并且无法将其识别为一个命令:
subprocess.check_call(['psql', '-q', '-U', 'myuser', '-h', 'localhost', '-c', '{}'.format(sql), '-c', '{}'.format('\gset'), '-c', '{}'.format('\if :is_uuid '), '-c', '{}'.format(sql2), '-c', '{}'.format('\endif'), 'dbase'], env={'PGPASSWORD': 'mypass'})
unrecognized value ":is_uuid" for "\if expression": Boolean expected
失败
我可以通过哪种方式从Python脚本执行psql命令?我的代码从PostgreSQL数据库插入和更新数据(使用psycopg2和cursor方法)。当我执行类似...的查询时,它工作正常……
[似乎您正在尝试通过类似于Meta-Command的psycopg2运行this question。 Psycopg2无法处理元命令,这就是为什么它引发此语法错误。