python - 无法使用python插入mysql表
问题描述
我正在尝试使用 python 中的 csv 文件在我的 sql 表中插入行。
有五列(id(autoincrement, primary, int),Event(int), Edition(int), Subscription(varchar), Daystogo(varchar)
我的 csv 有 4 列(事件、版本、订阅、Daystogo)。我想将这些插入表中,并以自动增量方式分配 id。
mydb = mysql.connector.connect(
user='user', password='password',
host='host',
database='opm')
mycursor = mydb.cursor()
csv_data=csv.reader("mycsvfile.csv")
for row in csv_data:
print(row)
mycursor.execute("INSERT INTO opm (Event, Edition, Subscription, Daystogo) VALUES (%s,%s,%s,%s)", (int,int,str, str))
这是我收到的错误
csv_data=csv.reader("mycsvfile.csv")
for row in csv_data:
print(row)
mycursor.execute("INSERT INTO opm (Event, Edition, Subscription, Daystogo) VALUES (%s,%s,%s,%s)", (int,int,str, str))
['m']
Traceback (most recent call last):
File "<ipython-input-51-5b5e2c804099>", line 4, in <module>
mycursor.execute("INSERT INTO opm (Event, Edition, Subscription, Daystogo) VALUES (%s,%s,%s,%s)", (int,int,str, str))
File "E:\Data Science\pyWork\PyProjects\Program\lib\site-packages\mysql\connector\cursor.py", line 547, in execute
psub = _ParamSubstitutor(self._process_params(params))
File "E:\Data Science\pyWork\PyProjects\Program\lib\site-packages\mysql\connector\cursor.py", line 430, in _process_params
"Failed processing format-parameters; %s" % err)
ProgrammingError: Failed processing format-parameters; Python 'type' cannot be converted to a MySQL type
对于代码
mycursor.execute("INSERT INTO opm (Event, Edition, Subscription, Daystogo) VALUES (%s,%s,%s,%s)")
错误是
ProgrammingError: 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 '%s,%s,%s,%s)' at line 1
请帮助我如何在mysql表中插入行
解决方案
假设您的 CSV 有四列,
mycursor.execute("INSERT INTO opm (Event, Edition, Subscription, Daystogo) VALUES (%s,%s,%s,%s)", row)
应该可以工作(第二个参数需要是一个列表或一个元组,其中包含要绑定到占位符的元素;由于您有四个占位符,因此您需要一个四元素列表或数据元组(不是数据类型!)。
推荐阅读
- c# - 如何避免 Winform 自动调整大小导致控件被裁剪?
- docker - 使用 Docker Compose 在 Docker 镜像之间共享文件夹和 Python 文件
- c# - 在 ASP.NET Core 2.1 中加载 appsettings.{envName}.json 文件
- php - 动态/递归 SQL 排序依据
- haskell - Haskell 子集递归
- javascript - 将 D3 年映射到 x 轴
- android - 查询中的 SQLite“排序依据”给出了错误的顺序
- excel - 在excel中为重复项添加后缀
- java - Java 数组和冒泡排序
- javascript - 如何在脚本函数中使用表单的值