Insert a list into mysql database
mysql-python, python
Solution
Don't use concatenation, use SQL parameters:
query = "INSERT INTO round1 (details) VALUES (%s)"
c = conn.cursor()
c.executemany(query, [(r,) for r in results])
Your code tried to concatenate a whole list with a string; you can only concatenate strings to strings. But to insert multiple rows for each value, you need to run an `INSERT` statement per entry in `results`.
Using SQL parameters here has several advantages:
- You leave quoting the value up to the database, avoiding SQL injection attacks.
- The database can reuse the query plan for the SQL statement, optimizing database performance.
- You can use `cursor.executemany()` to run the same query with different values, all with one call.
The `cursor.executemany()` call here takes each 'row' found in the second argument, taking the values from each row to run a separate `INSERT` statement.
Problem
I have this list I am trying to insert into my database. I have tried many other methods I found on Google or here but none seems to work. ``` results = ['match number 1','match number 2','match number 3'] query = "INSERT INTO round1 (details) VALUES (" query = query+"'"+results+"')" x = conn.cursor() x.execute(query) conn.commit() ``` I keep getting this error ``` Type Error: cannot concatenate 'str' and 'list' objects ``` Can anyone tell me what I am doing wrong?