Inserting a Python datetime.datetime object into MySQL

后端 未结 7 1277
Happy的楠姐
Happy的楠姐 2020-11-27 11:26

I have a date column in a MySQL table. I want to insert a datetime.datetime() object into this column. What should I be using in the execute statement?

7条回答
  •  感动是毒
    2020-11-27 11:31

    If you're just using a python datetime.date (not a full datetime.datetime), just cast the date as a string. This is very simple and works for me (mysql, python 2.7, Ubuntu). The column published_date is a MySQL date field, the python variable publish_date is datetime.date.

    # make the record for the passed link info
    sql_stmt = "INSERT INTO snippet_links (" + \
        "link_headline, link_url, published_date, author, source, coco_id, link_id)" + \
        "VALUES(%s, %s, %s, %s, %s, %s, %s) ;"
    
    sql_data = ( title, link, str(publish_date), \
                 author, posted_by, \
                 str(coco_id), str(link_id) )
    
    try:
        dbc.execute(sql_stmt, sql_data )
    except Exception, e:
        ...
    

提交回复
热议问题