Saimu
Saimu

Reputation: 1362

SQL : How to update existing value with variable

My goal is to up update the table so the new value (new_cost) is added to the existing one. Sorry if this question is dumb. And here's my function to update my table.

def db_update(new_cost, account):
    """ update the cost of an account
    """
    cursor.execute('''
    UPDATE transactions SET cost = cost + new_cost = ? WHERE account = ?
    ''', (new_cost, account))
    connection.commit()  

Upvotes: 1

Views: 2445

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1269773

You don't need new_cost in the string at all. It is being passed as a parameter:

def db_update(new_cost, account):
    """ update the cost of an account
    """
    cursor.execute('''
    UPDATE transactions SET cost = cost + ? WHERE account = ?
    ''', (new_cost, account))
    connection.commit()

This assumes that you want to increment the value of cost by new_cost. If you want to replace it, just use SET cost = ? for the set statement.

Upvotes: 2

ant_iw3r
ant_iw3r

Reputation: 222

Break your string and add the variable. When the SQL engine receives the command the variable value will be embedded in your string.

'UPDATE transactions SET COST = cost + ' + new_cost + 'rest of query string'.  

Upvotes: 0

Related Questions