-->

MySQL ON DUPLICATE KEY UPDATE with all variables

2019-08-31 05:18发布

问题:

I have below MySQL insert statement which I want to update all the fields(except for the primary key) if a record exists. Because there are up to 80 columns, I don't want to write the key and value pairs one by one. Could anyone help on this?

Below is my code:

 # Save item to database
def process_item(self, item, _):
    with self.conn.cursor() as c:
        c.execute(self.query(item), item.values())
def query(self, item):
    return "INSERT INTO income_statement ({columns}) VALUES ({values}) ON DUPLICATE KEY UPDATE ({columns}) = VALUES({columns})".format(
        columns=', '.join(item.keys()),
        values=', '.join(['%s'] * len(item))
    )

I got this error:

ProgrammingError: (1064, u"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(unit_name, fd_stock_dividend, fd_administration_fee, fd_depreciation, fd_divide' at line 1")