简体   繁体   English

如何使用Python将datetime插入sqlite3数据库?

[英]How to insert datetime into sqlite3 database using Python?

I would like to insert datetime into sqlite using Python. 我想使用Python将datetime插入sqlite。

I tried using Python's datetime and strftime but it didn't work. 我尝试使用Python的datetime和strftime,但是没有用。

Test's time field has the type of 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'": syntax error [SQL: INSERT INTO test (time) VALUES ('2019-05-19 17:14:25')] RuntimeError:(sqlite3.OperationalError)在“'2019-05-19 17:14:25'”附近:语法错误[SQL:INSERT INTO测试(时间)值('2019-05-19 17:14:25')]

You could use :- 您可以使用:-

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

The column type is basically irrelevant as in SQLite you can store any type of value in any type of column. 列类型基本上是无关紧要的,因为在SQLite中,您可以在任何类型的列中存储任何类型的值。

With the exception of the special rowid column or an alias of the rowid column (if the column is defined using INTEGER PRIMARY KEY then it is an alias of the rowid column (or with the AUTOINCREMENT keyword)). 用特殊的例外ROWID列或ROWID列的别名(如果列是使用定义INTEGER PRIMARY KEY则它是ROWID列的别名(或与AUTOINCREMENT关键字))。 An alias of the rowid column must be an integer up to 64 bit signed. rowid列的别名必须是最大为64位带符号的整数。

Working Example 工作实例

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

Result :- 结果:-

 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 

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

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