python 编码 mysql :(

2021-12-27 00:00:00 python encoding mysql

我有以下 python 脚本 (tes.py):

I have the follow python script (tes.py):

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import MySQLdb

query = "INSERT INTO test(test) VALUES ('ñ')"
print query + "
"

conn = MySQLdb.connect (host = "localhost", user = "ibrick", passwd = "x", db = "ibrick", charset="utf8")
conn.names="utf8"
cursor = conn.cursor()
cursor.execute (query);
cursor.close ()
conn.commit ()

文件编码utf-8:

 $ file -i tes.py 
tes.py: text/x-java charset=utf-8

系统编码 UTF:

#locale
LANG=es_AR.UTF-8
LC_CTYPE="es_AR.UTF-8"
LC_NUMERIC="es_AR.UTF-8"
LC_TIME="es_AR.UTF-8"
LC_COLLATE="es_AR.UTF-8"
LC_MONETARY="es_AR.UTF-8"
LC_MESSAGES="es_AR.UTF-8"
LC_PAPER="es_AR.UTF-8"
LC_NAME="es_AR.UTF-8"
LC_ADDRESS="es_AR.UTF-8"
LC_TELEPHONE="es_AR.UTF-8"
LC_MEASUREMENT="es_AR.UTF-8"
LC_IDENTIFICATION="es_AR.UTF-8"
LC_ALL=
echo "ñññ" > /tmp/test.txt

file /tmp/test.txt 
/tmp/test.txt: UTF-8 Unicode text

MYsql表编码UTF8:

MYsql table encoding UTF8:

mysql> show create table test;
+-------+----------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                 |
+-------+----------------------------------------------------------------------------------------------+
| test  | CREATE TABLE `test` (
  `test` varchar(10) default NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 | 
+-------+----------------------------------------------------------------------------------------------+

控制台输出正常:

#./tes.py 
INSERT INTO test(test) VALUES ('ñ')

问题:

脚本不会在表中插入 ñ ..它插入了一个坏字符:

The script doesn't insert ñ in the table.. it inserts a bad character:

select * from test;
+------+
| test |
+------+
| �    | 
| �    | 
| �    | 
| �    | 
| �    | 
| �    | 
| �    | 
+------+
7 rows in set (0.00 sec)

有人帮我吗??

提前致谢!

推荐答案

尝试添加 'use_unicode'.

Try adding 'use_unicode'.

秘诀是在你的连接中添加一个字符集=utf8"参数,并且 use_unicode=True.来源

The secret ingredient is to add a charset="utf8″ to your connection parameters, and use_unicode=True. Source

db = MySQLdb.connect(host=DB_HOST, user=DB_USER, passwd=DB_PASS, db=DB_NAME, charset="utf8", use_unicode=True)

相关文章