blu*_*inc 2 python mysql-python
我正在尝试将这个列表插入到我的数据库中。我尝试过在谷歌或这里找到的许多其他方法,但似乎都不起作用。
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()
Run Code Online (Sandbox Code Playgroud)
我不断收到此错误
Type Error: cannot concatenate 'str' and 'list' objects
Run Code Online (Sandbox Code Playgroud)
谁能告诉我我做错了什么?
不要使用连接,使用 SQL 参数:
query = "INSERT INTO round1 (details) VALUES (%s)"
c = conn.cursor()
c.executemany(query, [(r,) for r in results])
Run Code Online (Sandbox Code Playgroud)
您的代码尝试将整个列表与字符串连接起来;您只能将字符串连接到字符串。但要为每个值插入多行,您需要为中的每个条目INSERT运行一条语句。results
在这里使用 SQL 参数有几个优点:
cursor.executemany()不同的值运行相同的查询,所有这些都只需一次调用。这里的调用cursor.executemany()采用第二个参数中找到的每个“行”,从每行中获取值来运行单独的INSERT语句。