我使用的是:Python2.7 / MySQLdb 1.2.3
当我使用 MySQLdb.cursors 执行时INSERT IGNORE INTO reporter('张三', '2013-11-11'), ('张三', '2013-11-11')
,
它会出现这样的 UnicodeEncodeError 错误,它在显示警告时发生
File "/usr/local/lib/python2.7/dist-packages/MySQL_python-1.2.3-py2.7-linux-i686.egg/MySQLdb/cursors.py", line 224, in executemany
if not self._defer_warnings: self._warning_check()
File "/usr/local/lib/python2.7/dist-packages/MySQL_python-1.2.3-py2.7-linux-i686.egg/MySQLdb/cursors.py", line 92, in _warning_check
warn(w[-1], self.Warning, 3)
File "/usr/lib/python2.7/warnings.py", line 29, in _show_warning
file.write(formatwarning(message, category, filename, lineno, line))
File "/usr/lib/python2.7/warnings.py", line 38, in formatwarning
s = "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 17-18: ordinal not in range(128)
我应该怎么办?
这是我的代码:
# -*- coding: utf-8 -*-
import MySQLdb
db_conn = MySQLdb.connect(
host='localhost', user='root', passwd='', charset='utf8', db='test')
cursor = db_conn.cursor()
cursor.executemany(
'INSERT IGNORE INTO unicode_test values(%s, %s)',
[('张三', '2013-11-11'), ('张三', '2013-11-11')])
db_conn.commit()
cursor.close()
db_conn.close()
它来了
Traceback (most recent call last):
File "/home/cooper/Document/20131106.py", line 9, in <module>
[('张三', '2013-11-11'), ('张三', '2013-11-11')])
File "/usr/local/lib/python2.7/dist-packages/MySQL_python-1.2.3-py2.7-linux-i686.egg/MySQLdb/cursors.py", line 224, in executemany
if not self._defer_warnings: self._warning_check()
File "/usr/local/lib/python2.7/dist-packages/MySQL_python-1.2.3-py2.7-linux-i686.egg/MySQLdb/cursors.py", line 92, in _warning_check
warn(w[-1], self.Warning, 3)
File "/usr/lib/python2.7/warnings.py", line 29, in _show_warning
file.write(formatwarning(message, category, filename, lineno, line))
File "/usr/lib/python2.7/warnings.py", line 38, in formatwarning
s = "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 17-18: ordinal not in range(128)
[Finished in 0.2s with exit code 1]
这是我在 MariaDB 10.0 中使用的表
CREATE TABLE `unicode_test` (
`name` varchar(10) NOT NULL,
`date_of` date NOT NULL,
PRIMARY KEY (`name`,`date_of`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;