如何使用 cursor.execute() 中的"dt"来获取 PostgreSQL 中的表?(姜戈)



在Django中,我试图在cursor.execute()中使用dt来获取PostgreSQL中的表,如下所示:

# "views.py"
from django.http import HttpResponse
from django.db import connection
def test(request):
cursor = connection.cursor()
cursor.execute('''dt''') # Here
row = cursor.fetchone()
print(row)

return HttpResponse("Test")

但是,我得到了以下错误:

django.db.utils.ProgrammingError:"处或附近的语法错误\">
LINE 1:\dt

因此,我将cursor.execute('''dt''')替换为cursor.execute('''\dt'''),如下所示:

# "views.py"
from django.http import HttpResponse
from django.db import connection
def test(request):
# ...    
cursor.execute('''\dt''') # Here
# ...    
return HttpResponse("Test")

但是,我仍然得到以下错误:

django.db.utils.ProgrammingError:"处或附近的语法错误\">
LINE 1:\dt

那么,如何在cursor.execute()中使用dt来获取PostgreSQL中的表?

您可以使用纯SQL列出表,而不需要psql。

cursor.execute('''
select *
from pg_catalog.pg_tables
where schemaname = '<your_schema_name>';
''')

不能将dt命令用作postgresql查询。dt是客户端psql命令。PostgreSQL只能处理SQL命令(如SELECTINSERTALTER…(

但有一些方法:

  1. 使用参数-E运行psql。这意味着回声所有
  2. 运行选定的反斜杠命令(如dt(
  3. psql打印结果(以及为获取结果而生成的SQL查询(
  4. 从Django执行此查询

最新更新