I need to update columns values in csv to mysql database and the csv values are dynamic for one file it may be 10 columns and for other it may be 5 columns.
my understanding in python we need to use list also this question raised earlier is similar to my requirement but here the values are static so it can be predefined where’s in my case being dynamic need to a solution to have %%s under VALUES to be multiplied according to my column values dynamically.
MySQL Dynamic Query Statement in Python
ds_list=['name','id','class','chapter','MTH','YEAR'] vl_list=['xxxxx','978000048','x-grade','Science',mar,2017] sql = 'INSERT INTO ann1 (%s) VALUES (%%s, %%s, %%s, %%s, %%s, %%s)' % ','.join(ds_list) cur.execute(sql, vl_list) conn.commit()
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
So, if you have two lists, one with headers and the other with values – you can create yourself dynamic INSERT query.
query_placeholders = ', '.join(['%s'] * len(vl_list)) query_columns = ', '.join(ds_list) insert_query = ''' INSERT INTO table (%s) VALUES (%s) ''' %(query_columns, query_placeholders)
and then execute & commit your query by passing list with values in query.
cursor.execute(insert_query, vl_list)
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0