【问题标题】:How insert a list as a column in MySQL with Python?如何使用 Python 在 MySQL 中将列表作为列插入?
【发布时间】:2018-08-28 12:32:14
【问题描述】:

所以基本上我有这个列表:

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

欢迎任何建议!

【问题讨论】:

  • 我已经看到这个链接了,我在搞什么?
  • 为什么表中有world123 而不是world
  • @DavidWinder 我的错误对不起
  • @DavidWinder 这有关系吗?

标签: python mysql sql python-2.7 list


【解决方案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)

【讨论】:

  • 真丢脸,我刚刚注意到我写的是“%”而不是“(%)”。我现在没有错误,但没有插入数据库
  • 您可能需要commit进行交易。
猜你喜欢
  • 1970-01-01
  • 2013-04-19
  • 2021-01-05
  • 2013-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-17
  • 1970-01-01
相关资源
最近更新 更多