import pymysql import csv import pandas as pd con=pymysql.connect(host='localhost',user='root',port=3306,password='123456',charset="utf8",database='xscj') cur=con.cursor() with open('student.csv',encoding="utf-8") as f: gay=[tuple(row)for row in csv.reader(f,delimiter=',')] print(gay) sql="insert into stu(sno,name,major,born,nian,money) values(?,?,?,?,?,?)" cur.executemany(sql,gay) cur.execute("show stu") con.commit() con.rollback() cur.close() con.close()为什么运行会报错
时间: 2024-03-09 09:50:31 浏览: 52
python-pandas-2.0.3及其依赖包+sqlalchemy-2.0.30及其依赖包+pymysql-1.1.0
你没有正确地指定数据库表格的名称,这会导致执行 SQL 语句时出现语法错误。具体来说,代码中的 `cur.execute("show stu")` 应该改为 `cur.execute("select * from stu")` 或者 `cur.execute("show tables")`,才能正确地查询数据库中的表格信息。另外,你需要在 SQL 语句中指定要插入的字段,例如:`sql="insert into stu(sno,name,major,born,nian,money) values(%s,%s,%s,%s,%s,%s)"`。修改后的代码如下:
```python
import pymysql
import csv
import pandas as pd
con = pymysql.connect(host='localhost', user='root', port=3306, password='123456', charset="utf8", database='xscj')
cur = con.cursor()
with open('student.csv', encoding="utf-8") as f:
data = [tuple(row) for row in csv.reader(f, delimiter=',')]
print(data)
sql = "insert into stu(sno, name, major, born, nian, money) values(%s, %s, %s, %s, %s, %s)"
cur.executemany(sql, data)
cur.execute("select * from stu")
result = cur.fetchall()
print(result)
con.commit()
cur.close()
con.close()
```
注意,这段代码仅供参考,具体的修改取决于你的数据库结构和数据格式。
阅读全文