【问题标题】:How to programatically get table structure with pyscopg2如何使用 psycopg2 以编程方式获取表结构
【发布时间】:2016-09-25 11:44:15
【问题描述】:

当我执行程序 application.py 时,我得到这个错误:

psycopg2.ProgrammingError
ProgrammingError: ERREUR:  erreur de syntaxe sur ou près de « "/d" »
LINE 1: "/d" carto."BADGES_SFR"

(英文“ProgrammingError: ERREUR: syntax error at or near « "/d" » ")我这个程序的目标是获取表结构

这是以下代码application.py

#!/usr/bin/python 2.7.6
# -*- coding:utf-8 -*-
import os
import sys
from flask import Flask,render_template
import psycopg2
reload(sys)  
sys.setdefaultencoding('utf8')
app = Flask(__name__)

@app.route('/')
def fihoum():
    conn = psycopg2.connect(database="carto", user="postgres", password="daed5Aemo", host="192.168.12.54")
    cur = conn.cursor()
    #cur.execute("SELECT * FROM carto.\"BADGES_SFR\"")
    cur.execute("/d carto.\"BADGES_SFR\"")
    rows = cur.fetchall()
    return render_template('hello.html', titre="Données du client BADGES_SFR !",mots=rows)

if __name__=="__main__":
    app.run(host=os.getenv('IP', '0.0.0.0'), 
            port=int(os.getenv('PORT',5000)),
            debug=True)

【问题讨论】:

  • 它是否与 cur.execute("SELECT * FROM carto.\"BADGES_SFR\"") 行一起运行?
  • 是的,它使用 cur.execute("SELECT * FROM carto.\"BADGES_SFR\"") 运行
  • cur.execute("\d carto.\"BADGES_SFR\"") 会按照@bakkal 的建议解决吗?
  • 我不这么认为,因为\d table_name是无效的SQL语法,ProgrammingError: syntax error at or near "\"

标签: python postgresql flask psycopg2


【解决方案1】:

首先是\d <table_name>(注意反斜杠\d不是/d),但这仅在psql交互式终端中可用

我对这个程序的[目标]是获取表结构

您可以使用SQL表information_schema.columns,它携带您想要的信息

SELECT column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_name = '<table_name>';

    column_name     |     data_type     | is_nullable 
--------------------+-------------------+-------------
 column_a           | integer           | YES
 column_b           | boolean           | NO

以下是可用列的列表:https://www.postgresql.org/docs/9.4/static/infoschema-columns.html

片段

import psycopg2
conn = psycopg2.connect(database='carto', user=..., password=...)

q = """                              
SELECT column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_name = %s;
"""

cur = conn.cursor()
cur.execute(q, ('BADGES_SFR',))  # (table_name,) passed as tuple
cur.fetchall()

# Example Output 
[('column_a', 'integer', 'YES'),
 ('column_b', 'boolean', 'NO'),
 ...,
]

Jinja2/Flask 集成提示:

考虑使用psycopg2.extras.DictCursor,它可以让您更轻松地根据 Flask 模板中的列名(dict 键)提取信息,因为您将拥有一个可以访问的 dict,例如使用row['data_type']row['column_name']等。

【讨论】:

  • @ZaafLafalaise 我能问一下什么对你有用吗?
【解决方案2】:

如果您只需要列description

>>> cur.execute('select * from t')
>>> description = cur.description
>>> print description
(Column(name='record_timestamptz', type_code=1184, display_size=None, internal_size=8, precision=None, scale=None, null_ok=None),)
>>> columns = description[0]
>>> print columns.name, columns.type_code
record_timestamptz 1184

对于数据类型名称,在应用程序启动时缓存pg_type 关系并使其成为字典:

cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)

cursor.execute ('select oid, * from pg_type')

pg_type = dict([(t['oid'], t['typname']) for t in cursor.fetchall()])

cursor.execute ('select * from t')

for t in cursor.description:
    print t.name, t.type_code, pg_type[t.type_code]

【讨论】:

    猜你喜欢
    • 2019-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    • 2010-11-26
    • 2017-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多