当我执行程序 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)
答案 0 :(得分:3)
首先它是**<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>**
(请注意反斜杠\d <table_name>
而不是\d
),但这只适用于psql
互动终端
我的[目标]这个程序是获取表结构
您可以使用包含所需信息的SQL表/d
information_schema.columns
以下是可供使用的列的列表:https://www.postgresql.org/docs/9.4/static/infoschema-columns.html
<强>段强>
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
Jinja2 / Flask集成的提示:
考虑使用psycopg2.extras.DictCursor
,它会让您更容易根据Flask模板中的列名(dict键)提取信息,因为您将拥有一个可以访问的字典,例如:使用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'),
...,
]
,row['data_type']
等
答案 1 :(得分:1)
如果您只需要列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]