问题
I'm attempting to use python to insert a timestamp into column created_by of a mysql db.
Here is my database table setup..
CREATE TABLE temps (
temp1 FLOAT, temp2 FLOAT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
temp1 and temp2 and populating correctly but receiving an error for the timestamp
Warning: Data truncated for column 'created_at' at row 1
cursor.execute("""INSERT INTO temps VALUES (%s,%s,%s)""",(avgtemperatures[0],avgtemperatures[1],st[2]))
((71.7116, 73.2494, None),)
Here is the section of python script that inserts information into the db.
#connect to db
db = MySQLdb.connect("localhost","user","password","temps" )
#setup cursor
cursor = db.cursor()
ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
sql = """CREATE TABLE IF NOT EXISTS temps (
temp1 FLOAT,
temp2 FLOAT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)"""
cursor.execute(sql)
#insert to table
try:
cursor.execute("""INSERT INTO temps VALUES (%s,%s,%s)""",(avgtemperatures[0],avgtemperatures[1],st[2]))
db.commit()
except:
db.rollback()
#show table
cursor.execute("""SELECT * FROM temps;""")
print cursor.fetchall()
((188L, 90L),)
db.close()
Here is a dump of the db:
Dumping data for table temps
temp1 temp2 created_at
71.7116 73.2494 0000-00-00 00:00:00
回答1:
You should have to set the datetime. Your created_at column will automatically be updated to the current time stamp at insertion. See documentation at Automatic Initialization and Updating for TIMESTAMP.
You statement should be
cursor.execute("""INSERT INTO temps VALUES (%s,%s,CURRENT_TIMESTAMP)""",(avgtemperatures[0],avgtemperatures[1]))
来源:https://stackoverflow.com/questions/19232025/mysql-timestamp-data-truncated-for-column