Search code examples
pythonpython-2.7sqliteapsw

How to update a field with APSW


I am trying to update the timestamp on a database entry when I use it and I can't seem to get the Update statement to work

    import apsw
    from datetime import datetime

    def updateTimestamp(primary, timestamp):
        tableName = 'Images'

        connection = apsw.Connection('Images')
        cursor = connection.cursor()

        sql = "UPDATE %s SET timestamp = %s WHERE id = %s" %(tableName, timestamp, primary)
        print "ok so far"
        cursor.execute(sql)

        if connection:
            connection.close()

    currentTime = datetime.now()
    #remove spaces from timestamp
    currentTime = str(currentTime).replace(' ', '')
    updateTimestamp(1, currentTime)

I am using apsw to try and update a field but it is not working I get the error

"apsw.SQLError: SQLError: near ":05": syntax error"

My table looks like:

sql = 'CREATE TABLE IF NOT EXISTS ' + tableName + '(id INTEGER PRIMARY KEY 
    AUTOINCREMENT, Name TEXT, Metadata TEXT, Mods TEXT, Certification TEXT, 
    Product TEXT, Email TEXT, notes TEXT, timestamp TEXT, ftpLink TEXT)'

Solution

  • You are constructing an SQL command like this:

    UPDATE Images SET timestamp = 2013-01-3121:59:00.427408 WHERE id = 1
    

    The correct syntax would look like this instead:

    UPDATE Images SET timestamp = '2013-01-31 21:59:00.427408' WHERE id = 1
    

    However, to avoid string formatting problems, you should use parameters:

    sql = "UPDATE %s SET timestamp = ? WHERE id = ?" % (tableName)
    cursor.execute(sql, (timestamp, primary))