如何在psycopg2中执行非sql命令

时间:2018-10-31 05:50:57

标签: python postgresql psycopg2

如何执行

之类的非sql命令
\connect
\dl
\dt
\du
\d+ table_name 

...等

在psycopg2中?

cur.execute("\dl")

尝试使用游标执行操作时,出现错误

syntax error at or near "\"
LINE 1: \dl

2 个答案:

答案 0 :(得分:2)

这些命令由psql命令行工具而不是PostgreSQL服务器实现。其中一些(例如\dt)具有SQL等效项(例如SELECT … FROM INFORMATION_SCHEMA.tables-details here),而其他一些(例如\connect)则没有。如果要连接到另一个Postgres服务器,请创建一个新的连接对象。

答案 1 :(得分:1)

这些非sql命令专用于psql - PostgreSQL interactive terminal。您无法使用psycopg2执行它们,但可以从您的应用程序运行psql。以下Python 3.6中的完整示例使用subprocess:

import psycopg2
import sys
import subprocess

conn = psycopg2.connect(host='localhost', dbname='test', user='postgres')
conn.autocommit = True

cur = conn.cursor()
cur.execute('create table my_table(id int primary key, str text)')

res = subprocess.run('psql -c "\d+ my_table" test postgres', stdout=subprocess.PIPE)
print(res.stdout.decode(sys.stdout.encoding))

输出:

                                  Table "public.my_table"
 Column |  Type   | Collation | Nullable | Default | Storage  | Stats target | Description 
--------+---------+-----------+----------+---------+----------+--------------+-------------
 id     | integer |           | not null |         | plain    |              | 
 str    | text    |           |          |         | extended |              | 
Indexes:
    "my_table_pkey" PRIMARY KEY, btree (id)