我正在尝试执行两个SQL命令(创建新模式和表),以一种方式使得如果执行失败可以回滚这两个命令。我连接的数据库是AWS Redshift。
create schema if not exists test_schema;
create table test_schema.test_table as select 1;
最初我尝试使用Python编程方式执行这些命令,使用了psycopg2和pyodbc,但是遇到了以下错误:
ERROR: schema "test_schema" does not exist
我发现它失败的原因是第一个命令没有被提交,所以我尝试打开自动提交模式,并用"begin/end"块包装语句来修复它,但这并没有帮助。
当我使用psql CLI运行以下命令时,一切都按预期工作(没有"schema does not exist"错误,并且在回滚后,模式和表都消失了):
dev=# begin;
BEGIN
dev=# create schema test_schema;
CREATE SCHEMA
dev=# create table test_schema.test_table as select 1;
SELECT
dev=# rollback;
ROLLBACK
我尝试通过在命令行中运行以下内容来获得相同的结果:
psql -c "begin; create schema test_schema; create table test_schema.test_table as select 1;"
这会导致相同的错误:
ERROR: schema "test_schema" does not exist
然而,当我将上述代码放入文件中并运行相同的命令时,这次使用-f选项,它就可以正常工作:
psql -f create_schema_and_table.sql
我的问题是:
"psql -c"和"psql -f"执行查询有什么区别?
如何使用Python以编程方式实现相同的结果?
非常感谢!