Add current time to table with QSqlQuery?

Question:

Below can not add current time into dateTime of test4 table , how to modify ?

query.exec_("INSERT INTO test values('[email protected]','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('[email protected]','abc1',dt"))
Asked By: Raylene

||

Answers:

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('[email protected]','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().

Answered By: musicamante

I wager an easier solution is to set a default in the create table sql query.
As of Sqlite v3.1.0 you can now add current_timestamp.
This will save you hassles of needless import when inserting to any table.

CREATE TABLE IF NOT EXISTS test4(
id varchar(50) PRIMARY KEY,
password varchar(50),
dateTime timestamp not null default current_timestamp
)

As shown in enter link description here

Answered By: mello
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.