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?
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:
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.
i keep getting this error Type Error: cannot concatenate 'str' and 'list' objects can anyone tell me what i am doing wrong ?
First of all, what you're doing wrong is trying to concatenate str and list objects. You can't do that: you can only concatenate a string with a string.
Secondly, use prepared statements, instead of string manipulation to communicate with your database. It will be less code for you, and more secure.
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.