使用python3将numpy整数类型插入sqlite [英] inserting numpy integer types into sqlite with python3

查看:109
本文介绍了使用python3将numpy整数类型插入sqlite的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将numpy整数对象的值插入python 3中的数据库的正确方法是什么?在python 2.7中,numpy数值数据类型可以干净地插入sqlite中,但在python 3中却没有.

What is the correct way to insert the values of numpy integer objects into databases in python 3? In python 2.7 numpy numeric datatypes insert cleanly into sqlite, but they don't in python 3

import numpy as np
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE foo (id INTEGER NOT NULL, primary key (id))")
conn.execute("insert into foo values(?)", (np.int64(100),)) # <-- Fails in 3

np.float类型在2和3中似乎仍然可以正常工作.

The np.float types seem to still work just fine in both 2 and 3.

    conn.execute("insert into foo values(?)", (np.float64(101),))

在python 2中,numpy标量整数数据类型不再是int的实例,甚至将整数值浮点数转换为int.

In python 2, the numpy scalar integer datatypes are no longer instances of int, even converting integer-valued floating point numbers to ints.

   isinstance(np.int64(1), int)  # <- true for 2, false for python 3

这就是为什么dbapi不再与numpy无缝协作的原因吗?

Is this why the dbapi no longer works seamlessly with numpy?

推荐答案

根据sqlite3文档:

According to sqlite3 docs:

要在SQLite中使用其他Python类型,必须将其调整为sqlite3模块支持的SQLite类型之一:NoneType,int,float,str,bytes.

To use other Python types with SQLite, you must adapt them to one of the sqlite3 module’s supported types for SQLite: one of NoneType, int, float, str, bytes.

因此您可以适应 np.int64 类型.您应该执行以下操作:

So you can adapt np.int64 type. You should do something like this:

import numpy as np
import sqlite3

sqlite3.register_adapter(np.int64, lambda val: int(val))
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE foo (id INTEGER NOT NULL, primary key (id))")
conn.execute("insert into foo values(?)", (np.int64(100),))

文档

这篇关于使用python3将numpy整数类型插入sqlite的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆