插入 mysql 数据库时间戳
insert into a mysql database timestamp
我的 python 脚本中有一部分需要将一些数据插入到 mysql 数据库示例中的 table 中:
insert_data = "INSERT into test (test_date,test1,test2) values (%s,%s,%s)"
cur.execute(insert_data,(test_date,test1,test2))
db.commit()
db.close()
我有几个问题,这个语法有什么不正确的地方,以及如何将 VALUES 更改为时间戳而不是字符串的 %s?请注意,数据库中的列名与我脚本中变量中存储的数据相同。
谢谢
试试这个:
import MySQLdb
import time
import datetime
ts = time.time()
timestamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
conn = MySQLdb.connect(host= "localhost",
user="root",
passwd="newpassword",
db="db1")
x = conn.cursor()
try:
x.execute("""INSERT into test (test_date,test1,test2) values(%s,%s,%s)""",(timestamp,test1,test2))
conn.commit()
except:
conn.rollback()
conn.close()
时间戳创建可以一行完成,不需要使用time.time(),只需:
from datetime import datetime
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
直接使用数据库NOW()
函数,例如
timestamp="NOW()"
insert_data = "INSERT into test (test_date,test1,test2) values (%s,%s,%s)"
cur.execute(insert_data,(test_date,test1,test2,timestamp))
db.commit()
db.close()
我的 python 脚本中有一部分需要将一些数据插入到 mysql 数据库示例中的 table 中:
insert_data = "INSERT into test (test_date,test1,test2) values (%s,%s,%s)"
cur.execute(insert_data,(test_date,test1,test2))
db.commit()
db.close()
我有几个问题,这个语法有什么不正确的地方,以及如何将 VALUES 更改为时间戳而不是字符串的 %s?请注意,数据库中的列名与我脚本中变量中存储的数据相同。
谢谢
试试这个:
import MySQLdb
import time
import datetime
ts = time.time()
timestamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
conn = MySQLdb.connect(host= "localhost",
user="root",
passwd="newpassword",
db="db1")
x = conn.cursor()
try:
x.execute("""INSERT into test (test_date,test1,test2) values(%s,%s,%s)""",(timestamp,test1,test2))
conn.commit()
except:
conn.rollback()
conn.close()
时间戳创建可以一行完成,不需要使用time.time(),只需:
from datetime import datetime
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
直接使用数据库NOW()
函数,例如
timestamp="NOW()"
insert_data = "INSERT into test (test_date,test1,test2) values (%s,%s,%s)"
cur.execute(insert_data,(test_date,test1,test2,timestamp))
db.commit()
db.close()