首页 > 解决方案 > 如何使用 Python 将日期时间插入 sqlite3 数据库?

问题描述

我想使用 Python 将日期时间插入 sqlite。

我尝试使用 Python 的 datetime 和 strftime 但它没有用。

测试的时间字段的类型为 Numeric (Datetime)。

from datetime import datetime as dt

rows = db.execute(
    'INSERT INTO test (time) VALUES (:time)',
    time=dt.now().strftime('%Y-%m-%d %H:%M:%S'))

RuntimeError: (sqlite3.OperationalError) near "'2019-05-19 17:14:25'": 语法错误 [SQL: INSERT INTO test (time) VALUES ('2019-05-19 17:14:25')]

标签: pythonpython-3.xsqlitedatetime

解决方案


你可以使用:-

rows = db.execute("INSERT INTO test (time) VALUES (datetime('now'))")

列类型基本上无关紧要,因为在 SQLite 中,您可以在任何类型的列中存储任何类型的值。

除了特殊的rowid列或 rowid 列的别名如果该列是使用定义的,INTEGER PRIMARY KEY则它是 rowid 列的别名(或使用 AUTOINCREMENT 关键字))。rowid 列的别名必须是最多 64 位有符号整数。

工作示例

import sqlite3
drop_sql = "DROP TABLE IF EXISTS test"
crt_sql = "CREATE TABLE IF NOT EXISTS test (time NUMERIC, time2 TEXT, time3 BLOB, time4 REAL, time5 INTEGER )"
db = sqlite3.connect("test.db")
rows = db.execute(drop_sql)
rows = db.execute(crt_sql)
rows = db.execute("INSERT INTO test VALUES(datetime('now'),datetime('now'),datetime('now'),datetime('now'),datetime('now'))")
cursor = db.cursor()
cursor.execute("SELECT * FROM test")
for row in cursor:
    print("Time is " + row[0], "\nTime2 is " + row[1],"\nTime3 is " + row[2], "\nTime4 is " + row[3],"\nTime5 is " + row[4])
db.commit()
db.close()

结果 :-

Time is 2019-07-13 08:59:28 
Time2 is 2019-07-13 08:59:28 
Time3 is 2019-07-13 08:59:28 
Time4 is 2019-07-13 08:59:28 
Time5 is 2019-07-13 08:59:28

推荐阅读