【问题标题】:SQL datatbase not accepting UTF -8 Characters [duplicate]SQL数据库不接受UTF -8字符[重复]
【发布时间】:2013-12-25 05:32:04
【问题描述】:

我有一个 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"

任何帮助将不胜感激。

【问题讨论】:

    标签: python mysql sql utf-8 mysql-python


    【解决方案1】:

    这不是数据库问题;您正在尝试将 Unicode 值插入到字节字符串中,从而触发隐式编码。

    这里不要使用字符串格式,而是使用 SQL 参数:

    sql = "INSERT INTO players (pid,position,club,points,price,availability,rating,name) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"
    params = (count, position, club, points, s, availability, rating, name)
    cur.execute(sql, params)
    

    这里%s 告诉MySQLdb 期望SQL 参数在哪里,然后您将参数作为单独的列表传递给cursor.execute()

    记得告诉数据库连接你想对 Unicode 值使用 UTF-8:

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

    【讨论】:

    • 天啊。非常感谢!!!
    【解决方案2】:

    似乎与this question 重复。只是对其他人来说,解决方案是“当你connect() 到你的数据库时,传递charset='utf8' 参数。”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-30
      • 2015-05-17
      • 1970-01-01
      • 2013-05-05
      • 2014-03-18
      相关资源
      最近更新 更多