1

I imported MySQLdb, and established a database connection.

I am having two lists like below:

var_list = ['INFY','WIPR','SUZY','BEL' .....]
var_list2 = ['infosys', 'wipro', 'suzlon', 'bharat electronics', .....]

Which I aim to insert into the database. Therefore I write the following two string:

var_string = ', '.join('?' * len(varlist))
var_string2 = ','.join('?' * len(varlist2))

Now I am trying to insert the values into a MySQL table which has the following columns: symbol(varchar), and company(varchar).

query_string = 'INSERT INTO table VALUES (%s, %s);' %(var_string,var_string2)

cur.execute(query_string, (varlist,varlist2))

This however does not work.

0

1 Answer 1

1

Based on your question I think you aim to do bulk insert. You can modify your code as follows but I strongly advice against that:

query_string = 'INSERT INTO table VALUES %s;'%(','.join('(%s,%s)'*len(varlist)))
flatten = tuple(x for xs in zip(varlist,varlist2) for x in xs)
cur.execute(query_string,flatten)

Here you will generate a query_string that looks like:

INSERT INTO table VALUES (%s,%s),(%s,%s),(%s,%s),(%s,%s),(%s,%s);

And then you fill it in with a tuple ('INFY','infosys','WIPR','wipro',...)


You can better use .executemany():

cur.executemany("INSERT INTO table VALUES (%s,%s);",zip(var_list,var_list2))

This will generate longer queries, but the result is both more elegant and safe.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.