基本上我有这个列表:
L1 = ['hel-lo', 'world123', 'bye', 'python']
我想将这个列表插入到我的 MySQL 表中,如下所示:
+-------------------------+
| words |
+-------------------------+
| hel-lo |
| world123 |
| bye |
| python |
+-------------------------+
实际上,我的列表由大约 1000 个元素组成。 我尝试了很多在 StackOverflow 上找到的东西,但没有任何效果。 (似乎元素正试图以这种格式“['string']”插入)。
我尝试的最后一个解决方案:
values = [list([item]) for item in L1]
cursor.executemany(u"INSERT INTO `table`(`data`) VALUES %s", values)
返回此错误:
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''hel-lo')' at line 1
欢迎任何建议!
最佳答案
查询中的值列表周围缺少括号(应为 VALUES (%s)
)。此外,list([item])
可以简化为 [item]
:
L1 = ['hel-lo', 'world', 'bye', 'python']
values = [[item] for item in L1]
cursor.executemany(u"INSERT INTO `instability`(`ap_name`) VALUES (%s)", values)
关于python - 如何使用 Python 在 MySQL 中将列表作为列插入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52058007/