0

只是想快速了解使用 psycopg2 将大量数据重新排列到 postgres 中的最佳方法,即最少的编码方法。我看过一些使用 cast 的东西,但我真的认为这会很困难,我可以在网上找到一些好东西。

示例有人口普查数据,其中包含 200 个变量,在 recarray 中读取了许多列的不同数据类型。我只想浏览使用列名和数据类型并输入到 postgres。

另外,如果有比 psycopy2 更好的东西,我愿意接受建议。

这就是我发现的,尽管它进入了 sqlight 和错误的方式。

elif driver=='sqlite3':
                    tups=cur.fetchall()
                    if len(tups)>0:
                            _cast = {types.BooleanType: numpy.bool,
                                    types.IntType: numpy.int32,
                                    types.LongType: numpy.int64,
                                    types.FloatType: numpy.float64,
                                    types.StringType: numpy.str,
                                    types.UnicodeType: numpy.str}
                            try:
                                    typelist=[_cast[type(tmp)] for tmp in tups[0]]
                            except KeyError:
                                    raise Exception("Unknown datatype")
                            res = numpy.core.records.array(tups)
                    else:
                            return None
            res=[res[tmp] for tmp in res.dtype.names]
    except BaseException:
4

1 回答 1

2

Psycopg 可以使用新的适配器(当您想将 Python 对象传递给 Postgres 时)或新的 typecaster(当您想从 Postgres 读取并获取 Python 对象时)进行扩展。

看起来您必须为 numpy 类型注册一些现有的适配器,例如:

>>> psycopg2.extensions.register_adapter(numpy.int32, psycopg2._psycopg.AsIs)
>>> psycopg2.extensions.adapt(numpy.int32(42)).getquoted()
'42'

>>> psycopg2.extensions.register_adapter(numpy.str, psycopg2._psycopg.QuotedString)
>>> psycopg2.extensions.adapt(numpy.str("Hi 'quote'")).getquoted()
"'Hi ''quote'''"

通过这些注册,您可以直接使用 numpy 类型作为查询参数。

您可以在邮件列表中获得更多详细信息和帮助。

于 2011-05-11T14:06:06.067 回答