PostgreSQL - 你如何获得列格式?

joh*_*ith 4 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
Run Code Online (Sandbox Code Playgroud)

, 得到光标并且可以运行类似的代码行

cur.execute('SELECT latitude, longitude, date from db')
table = cur.fetchall()
Run Code Online (Sandbox Code Playgroud)

根据我在http://initd.org/psycopg/docs/cursor.html上的理解,运行

print(cur.description)
Run Code Online (Sandbox Code Playgroud)

应该显示每列的 type_code。我怎么不明白这个?

我得到

(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))
Run Code Online (Sandbox Code Playgroud)

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

cur.execute('select column_name, data_type from information_schema.columns')
cur.fetchall()
cols = cur.fetchall()
Run Code Online (Sandbox Code Playgroud)

但这会返回一个空列表。

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

kha*_*son 5

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

例如,给定这个 DDL:

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


insert into foo (name, val) values ('narf', 1), ('poit', 2);
Run Code Online (Sandbox Code Playgroud)

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

select *
from information_schema.columns
where table_schema NOT IN ('information_schema', 'pg_catalog')
order by table_schema, table_name;
Run Code Online (Sandbox Code Playgroud)

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

SQL 小提琴

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

编辑:

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

#!/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'])
Run Code Online (Sandbox Code Playgroud)

我更喜欢使用DictCursors,因为我发现它们更容易使用,但它也应该与常规游标一起使用——您只需要更改访问行的方式。

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

print cur.description[0][1]
Run Code Online (Sandbox Code Playgroud)

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