使用MySQLDB插入时间戳

时间:2016-11-28 08:59:59

标签: python mysql datetime mysql-python

我在使用Python上的MySQLdb执行此特定SQL插入时遇到问题。我尝试插入的表的特定模式已使用以下约束创建:

Movie_Ratings(mid:integer,uid:integer,rating:integer,comments:string,timestamp:timestamp)

CREATE TABLE Movie_Ratings (
uid INT,
mid INT,
rating INT,
comments VARCHAR(200),
timestamp TIMESTAMP NOT NULL,
PRIMARY KEY (uid, mid),
FOREIGN KEY (uid) REFERENCES Users ON DELETE CASCADE,
FOREIGN KEY (mid) REFERENCES Movies ON DELETE CASCADE,
CONSTRAINT “ch_movie_rating” CHECK (rating BETWEEN 1 AND 5) )

执行SQL插入已经适用于没有非键约束和时间戳的表。这是代码:

import MySQLdb
import time
import random
import datetime
from datetime import datetime

def strTimeProp(start, end, format1, format2, prop):
    stime = time.mktime(time.strptime(start, format1))
    etime = time.mktime(time.strptime(end, format1))

    ptime = stime + prop * (etime - stime)

    return time.strftime(format2, time.localtime(ptime))


def randomDate(start, end, prop):
    return strTimeProp(start, end, '%m/%d/%Y %I:%M %p','%Y-%m-%d   %H:%M:%S', prop)

db = MySQLdb.connect("localhost","username","password","database")
x = db.cursor()
movie_command = "insert into Movie_Ratings  (mid,uid,rating,comments,timestamp) values(%s, %s, %s, %s, %s)"
movie_data = []
comments = ["I really like this movie","My son really enjoyed this movie","A family movie indeed","Bravo!","Impeccable character progression","Ingenious movie direction",
    "Not appropriate for the whole family","Too Romanticized","Kids didn't enjoy the movie","The director should go back to director school"]
#Number of movies in table        
for j in range(1,5043):
    #Random number of ratings/comments for each movie
    for i in range(1,random.randint(1,10)):
            tup = (j,random.randint(1,5),random.randint(1,5),random.choice(comments),randomDate("1/1/2008 1:30 PM","10/31/2016 4:50 AM", random.random()))
            movie_data.append(tup)

try:
        x.executemany(movie_command,movie_data)
        db.commit()
except:
        db.rollback()
db.close()

打印出movie_data时,评级均为1到5之间,时间戳的格式为YYYY-mm-dd HH:MM:SS。我试图将它存储为日期时间对象和字符串,但都没有工作。

有什么建议吗?我不知道为什么这里的数据无法插入到数据库中!谢谢!

0 个答案:

没有答案
相关问题