SQL:如何使用变量更新现有值

时间:2014-03-26 23:53:26

标签: python sql sqlite

我的目标是更新表格,以便将新值(new_cost)添加到现有表格中。对不起,如果这个问题很愚蠢。这是我更新表格的功能。

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()  

2 个答案:

答案 0 :(得分:0)

打破你的字符串并添加变量。当SQL引擎收到命令时,变量值将嵌入到字符串中。

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

答案 1 :(得分:0)

根本不需要字符串中的new_cost。它作为参数传递:

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()

这假设您要将cost的值增加new_cost。如果您要替换它,只需使用SET cost = ?语句{/ 1}}。

相关问题