An error occurred while inserting UTF-8 characters in python MySQLdb.

Source: Internet
Author: User
Tags python mysql

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

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.