gpt4 book ai didi

python - SQL 数据库不接受 UTF -8 字符

转载 作者:行者123 更新时间:2023-11-30 23:09:31 25 4
gpt4 key购买 nike

<分区>

我有一个 python 程序,我可以在其中访问 url 并提取数据。然后我将这些数据输入到 mysql 表中。 mysql 表有列 pid ,position,club, points,s,availability, rating,name 。我对 python 程序没有任何问题(我希望如此),但数据库显然不接受带有 UTF 字母的名称 ex: Jääskeläinen 。如何使数据库接受这些名称?我尝试使用给出的答案 here .但是程序仍然给我以下错误:

Traceback (most recent call last):
File "C:\Users\GAMER\Desktop\Padai\Fall 13\ADB\player_extract.py", line 49, in <module>
sql += "('{0}', '{1}', '{2}', '{3}', '{4}','{5}','{6}','{7}')".format(count,position,club, points,s,availability, rating,name)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-2: ordinal not in range(128)
excepted Goalkeepers Jääskeläinen West Ham 67 £5.5

我的 python 代码是这样的"

# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
from urllib import urlopen
from pprint import pprint
import MySQLdb
import traceback
import re
#fetch players list from site

url = "http://fantasy.premierleague.com/player-list/"
html = urlopen(url).read()


soup = BeautifulSoup(html)
h2s = soup.select("h2")
tables = soup.select("table")

first = True
title =""
players = []
for i,table in enumerate(tables):
if first:
title = h2s[int(i/2)].text
for tr in table.select("tr"):
player = (title,)
for td in tr.select("td"):
player = player + (td.text,)
if len(player) > 1:
players.append(player)

first = not first

##SQL connectivity and data entry

db = MySQLdb.connect(host="localhost", user="root", passwd="hassan28", db = "adbpro")

cur = db.cursor()

try:
count = 1
for i in players:
position, name, club, points, price = i
s = price[1:]
name = name.replace("'"," ")
rating = 4
availability = 1
sql = "INSERT INTO players (pid,position,club,points,price,availability,rating,name) VALUES "
try:
sql += "('{0}', '{1}', '{2}', '{3}', '{4}','{5}','{6}','{7}')".format(count,position,club, points,s,availability, rating,name)
cur.execute(sql)
count +=1
except UnicodeError:
traceback.print_exc()
print "excepted", position, name, club, points, price
continue
#print sql

db.commit()

except:
print sql
traceback.print_exc()
db.rollback()
cur.execute("SELECT * FROM PLAYERS")


print "done"

任何帮助将不胜感激。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com