pymysql.err.ProgrammingError: (1064, "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 'rank INT, name VARCHAR(255), count INT, PRIMARY KEY (id))' at line 1")
时间: 2023-07-01 21:16:22 浏览: 164
django.db.utils.ProgrammingError: (1146, u“Table‘’ doesn’t exist”)问题的解决
这个错误是由于使用了MySQL保留字`rank`作为列名,而MySQL在语法中解析`rank`时会出现问题。解决方法是将`rank`改为其他名称,例如`ranking`。
以下是修改后的代码:
```python
import requests
from bs4 import BeautifulSoup
import pymysql
# 爬取数据
url = 'http://www.mafengwo.cn/mdd/ranking/list?range=domestic&season=0'
res = requests.get(url)
soup = BeautifulSoup(res.text, 'html.parser')
items = soup.select('.item')
data = []
for item in items:
rank = int(item.select_one('.num').text.strip())
name = item.select_one('.title').text.strip()
count = int(item.select_one('.count').text.strip())
data.append((rank, name, count))
# 存入数据库
conn = pymysql.connect(host='localhost', user='root', password='password', database='mydb', charset='utf8')
cursor = conn.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS tourism_ranking (id INT NOT NULL AUTO_INCREMENT, ranking INT, name VARCHAR(255), count INT, PRIMARY KEY (id))')
cursor.executemany('INSERT INTO tourism_ranking (ranking, name, count) VALUES (%s, %s, %s)', data)
conn.commit()
cursor.close()
conn.close()
```
修改后的代码将`rank`改为`ranking`,并在SQL语句中也做了相应的修改,同时建议在使用MySQL时避免使用保留字作为列名。
阅读全文