bin
发布于

插入 MySQL 数据库时间戳

python 脚本中有一部分需要将一些数据插入到 mysql 数据库示例的表中:

  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 更改为 timestamp 而不是 %s?请注意,数据库中的列名与脚本中变量中存储的数据相同。

浏览 (17)
点赞
收藏
1条评论
bin
bin
试试这个: 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()
点赞
评论