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