简体   繁体   中英

Dynamic insert/update/select mysql python

I'm trying to make a query on a table, but values what i want to enter is dynamic. One time i want to enter 4 values in 4 columns, second time maybe i want to enter 5 values in 5 columns.
Like :

SELECT * FROM table_name WHERE column1 = x AND column2 = y

But sometime i need something like this
SELECT * FROM table_name WHERE column2 = x AND column6 = y AND column1 = z

Same at insert and update like this:
UPDATE table_name SET column1 = x, column7 = y WHERE column9 = z but, columns at SET and WHERE may be more or less.
This is what i made, but number of columns is static:
cur.execute("""UPDATE logs SET Log_Status = %s WHERE Log_Path = %s""", (value, pathLog))
Thanks!

In case params is a dictionary:

params = {'column1': 'value1', 'column2': 'value2'}

You can try something like this:

terms = ' AND '.join(f'{key} = %s' for key in params)
query = 'SELECT * FROM table_name WHERE ' + terms
args = (params.values())
cur.execute(query, args)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM