Below can not add current time into dateTime of test4 table , how to modify ?
query.exec_("INSERT INTO test values('abc@wdc.com','abc1',dt"))
from PyQt5.QtSql import QSqlDatabase, QSqlQuery
from datetime import datetime
database = QtSql.QSqlDatabase.addDatabase('QSQLITE')
database.setDatabaseName('test1.db')
database.open()
query = QSqlQuery()
query.exec_("CREATE TABLE IF NOT EXISTS test4(id varchar(50) PRIMARY KEY,password varchar(50),dateTime timestamp)")
dt=datetime.now()
query.exec_("INSERT INTO test VALUES('abc@wdc.com','abc1',dt"))
You are not adding the dt
variable, you're adding the "dt" string.
There are also two other problems in your code: you imported QSqlDatabase
but you're using QtSql.QSqlDatabase
, and you are adding the value to the test
table while the one you created is test4
.
from PyQt5.QtSql import QSqlDatabase, QSqlQuery
from datetime import datetime
database = QSqlDatabase.addDatabase('QSQLITE')
database.setDatabaseName('test1.db')
database.open()
query = QSqlQuery()
query.exec_("CREATE TABLE IF NOT EXISTS test4(id varchar(50) PRIMARY KEY,password varchar(50),dateTime timestamp)")
dt=datetime.now()
query.exec_("INSERT INTO test4 VALUES('abc@wdc.com','abc1','{}'".format(dt))
Consider that the above will use a natural string representation of the datetime object:
2020-11-12 14:32:13.471729
This requires the quotes around the variable, otherwise the space between the date and the time will be interpreted as a literal query space (used to separate commands), resulting in an error. You could even use the isoformat()
for a more standardized representation, allowing further reconversion to datetime objects using fromisoformat()
.