如何使用python翻译PostgreSQL OID

2024-05-16 06:29:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我在使用psycopg2 Python模块时遇到了一些问题。我编写了一个小代码,使用psycopg2模块从PostgreSQL表中提取一些信息。我想知道表中每列的数据类型:

import os, psycopg2, getpass, sys, string

userpass = getpass.getpass()

# Connect to the database
conn = psycopg2.connect("host=hostname dbname=db user=username password=%s" %  (userpass))
cur = conn.cursor()
cur.execute("SELECT * FROM database.table;")

fieldTypes = [desc[1] for desc in cur.description]

print fieldTypes

当我执行这段代码时,我得到一个整数列表(即oid)。有没有办法把它转换成更容易理解的东西(例如'str'、'int'、'bool'等等)。在


Tags: 模块代码import信息ospostgresqlconndatabase
1条回答
网友
1楼 · 发布于 2024-05-16 06:29:39

只要OID (Object Identifier)实际上是一个^{}(注册类型的OID子类型),就像您从函数^{}获得的一样,您可以通过简单的强制转换将“OID”转换为text。在

Postgres通常将数据类型regtype的值显示为text给用户。示例:

SELECT pg_typeof('2013-1-1'::date);
 pg_typeof
     -
 date

内部是OID:

^{pr2}$

如果您的客户机不这样做,您可以使用显式转换强制执行:

SELECT pg_typeof('2013-1-1'::date)::text;
SELECT 1082::regtype::text;

从系统目录获取所有列的类型

现在还不清楚你到底是如何检索这些类型的。请考虑以下查询以获取完整信息:

SELECT attname
     , atttypid::regtype AS base_type
     , format_type(atttypid, atttypmod) AS full_type
FROM   pg_catalog.pg_attribute
WHERE  attrelid = 'public.tbl'::regclass    your table name here
AND    attnum > 0
AND    NOT attisdropped
ORDER  BY attnum;

  attname   |          base_type          |         full_type
      +              -+              -
 age_id     | integer                     | integer
 age        | text                        | text
 ageabk     | character                   | character(2)
 foo        | boolean                     | boolean
 log_up     | timestamp without time zone | timestamp without time zone

注意,^{}显示包含修饰符的类型。在

相关问题 更多 >