inserting numpy integer types into sqlite with python3

前端 未结 2 1976
误落风尘
误落风尘 2020-12-10 05:37

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

相关标签:
2条回答
  • 2020-12-10 05:41

    Rather than:

    sqlite3.register_adapter(np.int64, lambda val: int(val))
    

    You can use:

    sqlite3.register_adapter(np.int64, int)
    
    0 讨论(0)
  • 2020-12-10 05:45

    According to sqlite3 docs:

    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.

    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),))
    

    Docs

    0 讨论(0)
提交回复
热议问题