Python operation MySQL requires installation of Python-mysql
Can be searched from the Internet, and the same as the normal Python package installation
After installation, the module name is MYSQLDB, can be used in Windows and Linux environment, the test is very useful,
But also found the annoying mess problem, finally used a few ways, solved!
I have used the following measures to ensure that MySQL output is not mess:
1 python file Set encoding utf-8 (file front plus #encoding =utf-8)
2 MySQL Database charset=utf-8
3 python connection mysql is plus parameter Charset=utf8
4 Set Python's default encoding to Utf-8 (sys.setdefaultencoding (Utf-8)
mysql_test.py
#encoding =utf-8import sysimport mysqldbreload (SYS) sys.setdefaultencoding ('Utf-8') DB=mysqldb.connect (user='Root', charset='UTF8') cur=db.cursor () Cur.execute ('Use mydb') Cur.execute ('select * from MYTB limit') F=file ("/home/user/work/tem.txt",'W') forIinchCur.fetchall (): F.write (str (i)) F.write (" ") F.close () cur.close ()
The above is a script on Linux, Windows is working properly!
Note: The configuration file settings for MySQL must also be configured as UTF8
Set the MySQL my.cnf file, set the default character set (usually in/etc/mysql/my.cnf) in the [Client]/[mysqld] section:
[Client]
Default-character-set = UTF8
[Mysqld]
Default-character-set = UTF8