python - 如何使用 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')]
解决方案
你可以使用:-
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
推荐阅读
- python - 打印 1 个十进制数的计算结果
- php - 如何在新标签页中打开链接?
- c# - System.Net.Http.HttpRequestException:400(错误请求)OnceSingleAsync FIREBASE
- python - 使用 32 位整数和操作数
- java - Firestore SetOptions.mergeFields 不存储字段
- ios - 让条件在 Firebase Observer 中工作
- c - 在 C 中洗牌
- spring - Spring/MongoDB/Junit:使用 Fongo 进行单元测试时出现空指针异常
- javascript - 如何将输入值分配给复选框值,然后计算检查总数?
- node.js - 如何跟踪使用 nightwatch 和 selenium 异步渲染的许多元素?