When using a third-party python mysql package to execute SQL statements containing UTF8 characters, the following errors may occur:
'Ascii 'codec can't encode character ...... '
Or
'Latin-1' codec can't encode character ...... '
In fact, you only need to note the encode before inserting:
Python statement:
01
# Coding = UTF-8
02
Import MySQLdb
03
Cc = 'ours'
04
Conn = MySQLdb. connect (
05
Host = "localhost ",
06
User = "root ",
07
Passwd = "root ",
08
Port = 3306,
09
Db = "test1 ",
10
Init_command = "set names utf8"
11
)
12
13
Cursor = conn. cursor ()
14
Cursor.exe cute ("insert into a values ('% s')" % (cc. encode ('utf-8 ')))
15
Conn. commit ()
Database Table creation statement:
1
Create table 'A '(
2
'Name'char (100) DEFAULT NULL
3
) ENGINE = InnoDB default charset = utf8
Result (in windows ):
01
Mysql> set names gbk;
02
Query OK, 0 rows affected (0.00 sec)
03
04
Mysql> select * from;
05
+ ------ +
06
| Name |
07
+ ------ +
08
| 1 |
09
| We |
10
+ ------ +
11
2 rows in set (0.00 sec)
12
13
Mysql>
Douban.com explained the problem as follows: www.2cto.com
Conn = MySQLdb. connect (host = host, user = user, passwd = password, db = db, init_command = "set names utf8 ")
Then use conn, So you no longer need to consider encoding.
Another benefit is that, if the intermediate timeout and MySQLdb are automatically reconnected, the new link can still be UTF-8.
You can also manually: cursor.exe cute ("set names UTF-8 ")
Author: xrzs