python - PostgreSQL - 你如何获得列格式?

标签 python postgresql psycopg2

我在 x86_64-unknown-linux-gnu 上使用 PostgreSQL 9.3.3,由 gcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-52) 编译,64 位。

我已经做了

psycopg2.connect

,得到光标,可以运行类似于

的代码行
cur.execute('SELECT latitude, longitude, date from db')
table = cur.fetchall()

据我了解 http://initd.org/psycopg/docs/cursor.html , 运行

print(cur.description)

应显示每列的类型代码。为什么我没有得到这个?

我明白了

(Column(name='column_name', type_code=1043, display_size=None, internal_size=-1, precision=None, scale=None, null_ok=None), Column(name='data_type', type_code=1043, display_size=None, internal_size=-1, precision=None, scale=None, null_ok=None))

我被建议的另一个解决方案是运行

cur.execute('select column_name, data_type from information_schema.columns')
cur.fetchall()
cols = cur.fetchall()

但这会返回一个空列表。

这就是我尝试过的。您对获取列格式有何建议?

最佳答案

information_schema.columns 应该为您提供列数据类型信息。

例如,给定此 DDL:

create table foo
(
  id serial,
  name text,
  val int
);


insert into foo (name, val) values ('narf', 1), ('poit', 2);

这个查询(过滤掉元表以获取您的表):

select *
from information_schema.columns
where table_schema NOT IN ('information_schema', 'pg_catalog')
order by table_schema, table_name;

将为表 foo 生成 4 行——我定义的三列,加上一个 FK。

SQL fiddle

关于 psycopg2,您所显示的与 information_schema 相关的代码看起来应该可以工作...代码的全部内容是什么?我还建议尝试在调试器中单步执行代码(内置的 pdb 没问题,但我会推荐 pudb ,因为它功能更全面且更易于使用,但仍然是终端基于。不过,由于它使用的底层模块,它只能在 *nix 平台上运行。

编辑:

我能够使用 psycopg2 和以下代码从 information_schema 获取 data_type 信息:

#!/usr/bin/env python

import psycopg2
import psycopg2.extras

conn = psycopg2.connect("host=<host> dbname=<dbname> user=<user> password=<password>")
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)

cur.execute("""select *
               from information_schema.columns
               where table_schema NOT IN ('information_schema', 'pg_catalog')
               order by table_schema, table_name""")

for row in cur:
    print "schema: {schema}, table: {table}, column: {col}, type: {type}".format(
        schema = row['table_schema'], table = row['table_name'],
        col = row['column_name'], type = row['data_type'])

我更喜欢使用 DictCursor,因为我发现它们更容易使用,但它也应该适用于常规游标——您只需要更改访问行的方式.

此外,关于 cur.description,它返回 元组元组。如果你想在那里获取 type_code,你可以这样做:

print cur.description[0][1]

您要查看的列的索引中的第一个维度,第二个维度是该列中的数据。 type_code 始终为 1。例如,您可以迭代外部元组并始终查看其第二项。

关于python - PostgreSQL - 你如何获得列格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27832289/

相关文章:

python - psycopg2.ProgrammingError : syntax error at or near "OR

python - 无法在 aws CDK 中找到 select_subnets 函数

python - PyPi站 pip 缺少sys,subprocess和timeit软件包

javascript - 如何在 Python 中更新 Bokeh 的 JavaScript 回调中的源?

sql - SQL 查询的 Spring Data R2DBC 参数条件绑定(bind)

database - PostgreSQL 中的部分索引何时更新?

python - cur.executemany 在字符串格式化期间并非所有参数都已转换

python - psycopg2.ThreadConnectionPool、uWSGI 和 Flask 的并发问题

python - 为什么Python中的像素值会自动变化?

postgresql - 使用 PostGreSQL 和 Persistent 将条目插入数据库