执行多个查询时,“ psql -c”和“ psql -f”有什么区别?

时间:2019-01-14 21:29:14

标签: sql amazon-redshift psycopg2 psql pyodbc

我正在尝试执行两个sql命令(创建新的架构和表),这种方式将在执行失败时启用两个命令的回滚。我要连接的数据库是AWS Redshift。

create schema if not exists test_schema;
create table test_schema.test_table as select 1;

最初,我尝试使用psycopg2和pyodbc使用python编程地执行这些命令,并得到以下错误:

ERROR:  schema "test_schema" does not exist

我意识到它会失败,因为第一个命令没有被提交,因此为了解决该问题,我尝试将自动提交模式设置为开,并用“ begin / end”块包装语句,这没有帮助。 / p>

当我使用psql CLI并运行以下命令时,一切都按预期工作(没有“ schema不存在”错误,并且在回滚之后,架构和表都消失了):

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

我的问题是:

  1. 使用“ psql -c”和“ psql -f”执行查询之间有什么区别?

  2. 如何使用python通过编程实现相同的结果?

非常感谢!

1 个答案:

答案 0 :(得分:0)

我不知道您在做什么错,您的“ psql -c”命令可以正常工作:

ads@diamond:~$ psql -c "begin; create schema test_schema; create table test_schema.test_table as select 1;" postgres
SELECT 1

psql将把整个字符串发送到服务器,并在一个事务中执行它。您的问题是您使用“开始”开始事务,但从未提交。因此,在psql运行结束时,所有更改都将回滚。下一个psql命令将找不到模式,也不会找到表。但是只要一切都停留在单个psql调用中,同一命令中的后续查询就可以看到新创建的对象。

您的查询字符串应改为:

begin; create schema test_schema; create table test_schema.test_table as select 1; commit;

或者,更简单:

create schema test_schema; create table test_schema.test_table as select 1;

两者都可以。