简体   繁体   English

在sqlite3数据库中插入datetime错误

[英]insert datetime in sqlite3 database error

I have a pandas dataframe with the following data types 我有一个具有以下数据类型的pandas数据框

var1            object
var2        datetime64[ns]
var3             object
var4            object
var5             int64
var6            float64

my schema in the sqlite3 data base is 我在sqlite3数据库中的架构是

CREATE TABLE IF NOT EXISTS "table_name" (
"var1" TEXT,
"var2" DATETIME,
"var3" TEXT,
"var4" TEXT,
"var5" INT,
"var6" REAL
);

my query in python looks lite this 我在python中的查询看起来很简单

query = 'insert into first_north4 (var1, var2, var3, var4, var5, var6) values (?, ?, ?, ?, ?, ?)'
values = [tuple(x) for x in df.values]
cur.executemany(query, values)

When executing the query I get this error msg 执行查询时出现此错误消息

sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type.

This is the datetime that fails, I can't figure out why 这是失败的日期时间,我不知道为什么

From the sqlite datatypes doc : sqlite数据类型doc

2.2. 2.2。 Date and Time Datatype 日期和时间数据类型

SQLite does not have a storage class set aside for storing dates and/or times. SQLite没有为存储日期和/或时间预留存储类。 Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values: 相反,SQLite内置的日期和时间功能可以将日期和时间存储为TEXT,REAL或INTEGER值:

  • TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS"). 文本为ISO8601字符串(“ YYYY-MM-DD HH:MM:SS.SSS”)。
  • REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 BC according to the proleptic 真实数字为儒略日数,根据多面手,自公元前4714年11月24日格林威治中午以来的天数
    Gregorian calendar. 阳历日历。
  • INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC. INTEGER as Unix Time,自1970-01-01 00:00:00 UTC以来的秒数。

Applications can chose to store dates and times in any of these formats and freely convert between formats using the built-in date and time functions. 应用程序可以选择以任何一种格式存储日期和时间,并使用内置的日期和时间功能在格式之间自由转换。

One option would be to convert var2 to a string before db insert (thus preserving the DATETIME datatype in the database) as described here . 一种选择是为描述VAR2转换为字符串数据库插入之前(从而保留在数据库中的datetime数据类型) 在这里 There are other options, and a search on this forum for "datetime64 sqlite" should provide other approaches. 还有其他选择,在此论坛上搜索“ datetime64 sqlite”应提供其他方法。

I found a working solution for me (regarding date object), hopefully this will help somebody else in the future. 我为我找到了一个可行的解决方案(关于日期对象),希望这会在将来对其他人有所帮助。 Fully working example below in python3 以下python3中的完整工作示例

import pandas as pd
import datetime as dt
import sqlite3

# est conn (creates db if not exist)
db = 'db_test.db'
conn=sqlite3.connect(db,
detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
cur = conn.cursor()

# create table
query='CREATE TABLE IF NOT EXISTS test(i INT, f REAL, d DATE)'
cur.execute(query)

# some specific datatypes to dataframe
i = [4 ,2 ,44]
f=[1.23,123.2,2.2222]
d = [dt.date.today(),dt.date.today(),dt.date.today()]
df = pd.DataFrame(data=[i,f,d],index = ['i','f','d']).T
print(df)
print(df.dtypes)
print(type(df['i'].values[0]))
print(type(df['f'].values[0]))
print(type(df['d'].values[0]))

# insert
query = 'insert into test (i, f, d) values (? ,?, ?)'
values = [tuple(x) for x in df.values]
print(values)
cur.executemany(query, values)
conn.commit()

# test types when querying the db
query = cur.execute('SELECT * from test')
cols = [column[0] for column in query.description]
data = pd.DataFrame.from_records(data=query.fetchall(), columns=cols)
print(data)
print(data.dtypes)
print(type(data['i'].values[0]))
print(type(data['f'].values[0]))
print(type(data['d'].values[0]))

# close conn
cur.close()
conn.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM