Troubleshooting python connection MySQL error problem

Source: Internet
Author: User
Tags python script

Troubleshooting python connection MySQL error problem


Recently ran Python script encountered a problem when the SQL statement in Chinese, executed the Python script following error:

Traceback (most recent):

File "kpi_daily_report.py", line 356, in <module>

result = Cal (line, sys.argv[1], sys.argv[2])

File "kpi_daily_report.py", line 324, in Cal

result = run (SQL)

File "kpi_daily_report.py", line +, in run

RTN = Conn31.selectall (SQL)

File "/data0/home/yangjing150/test/kpidaily222/mysql_db_connector.py", line +, in SelectAll

Raise ex;

Unicodeencodeerror: ' latin-1 ' codec can ' t encode characters in position 204-206:ordinal not in range (256)


After query and test, the following three points can solve the problem perfectly

1. Python script setting utf-8 as the default character set

Import OS, sys

Import MySQL

Reload (SYS)

Sys.setdefaultencoding ("Utf-8")


2. When MySQL is connected, set the character set charset= ' UTF8 '

3. The cursor executes the SQL statement, plus the setting of the character set UTF8

Self.cursor.execute (' SET NAMES utf8; ')


The specific code is as follows:

def selectall (self, CommandText):

RTN = None

Try

If Self.auto and Self.con = = None:

Self.con = mysql.connect (host = self.host, port = Self.port,

user = Self.user, passwd = self.passwd, db = Self.db,

Connect_timeout = 1,charset= ' UTF8 ')

If Self.con:

Self.cursor = Self.con.cursor ()

self.cursor.execute (' SET NAMES utf8; ')

If Self.cursor:

self.cursor.execute (' SET NAMES utf8; ')

Self.cursor.execute (CommandText)

RTN = Self.cursor.fetchall ()

Except Exception as ex:

Raise ex;

Finally

If Self.auto:

Self.close ()

Return RTN


This article is from the "rookie site" blog, please be sure to keep this source http://yangjingangel.blog.51cto.com/8351501/1934664

Troubleshooting python connection MySQL error problem

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.