Search code examples
mysqlpython-3.xflask-mysql

Mysql converts varchar to year while update


I have a query for updating varchar time field and I don't want to keep them in DATE format. My string date format is yyyy-mm-dd is 2018-05-13.

query = "UPDATE SchedulePlaylist
    SET start = %s ,end = %s
    WHERE playlist_id = %s AND schedule_id = %s" % (
                str(start), str(end), playlist_id, schedule_id)

This are contents of functions after updating the database.

But my actual table looks like this

how can I prevent this conversion. I am using python and flask_mysqldb connector


Solution

  • The proper approach is to use parameters to pass the values in. This could get awkward, because of the date/string issues.

    The naive solution in your case is to add single quotes around values:

    query = "UPDATE SchedulePlaylist
        SET start = '%s', end = '%s'
        WHERE playlist_id = %s AND schedule_id = %s" % (
                    str(start), str(end), playlist_id, schedule_id)
    

    Your code is treating 2018-04-30 as arithmetic and producing 1984. The single quote cause them to be represented as a string.

    What you should really do is fix the table, so the columns have the correct type. A string stored as YYYY-MM-DD is a reasonable type if you have to store the date as a string. Otherwise use date. However, that doesn't fix your update problem.

    The better solution is to use parameters, and that is simple. The parameters go in the execute call:

    query = """
    UPDATE SchedulePlaylist
        SET start = ?, end = ?
        WHERE playlist_id = ? AND schedule_id = ?
    """;
    
    cursor.execute(query, (str(start), str(end), playlist_id, schedule_id));