作業系統:windows
開發環境:python 2.5 + pymssql 1.0.1
資料庫:Sql Server 2005 中文
Python 使用一段時間了, 最頭疼的還是中文編碼問題。今天用 pymssql 寫一些資料到 Sql Server 資料庫裡面時出現了問題。
# -*- coding: UTF-8 -*-
import pymssql
conn = pymssql.connect(host='192.168.10.167', user='sa', password='sa', database='Test')
cur = conn.cursor()
cmd = "INSERT INTO Demo VALUES('索引測試')";
cmd = cmd.decode('utf-8')
print cmd
cur.execute(cmd)
conn.commit()
conn.close()
print 顯示都是正確的, 但是 execute 報錯
>>>
INSERT INTO Demo VALUES('索引測試')
Traceback (most recent call last):
File "E:\Workshop\python\overlay\test.py", line 15, in <module>
cur.execute(cmd)
File "C:\Python25\lib\site-packages\pymssql.py", line 185, in execute
self._source.execute_query(operation, params)
SystemError: \loewis\25\python\Objects\stringobject.c:4465: bad argument to internal function
但是去掉 cmd = cmd.decode('utf-8') 後寫入資料又是亂碼 "緔㈠紩嫻嬭瘯"
調試了一下午,將
# -*- coding: utf-8 -*-
改為
# -*- coding: cp936 -*-
或
# -*- coding: gb2312 -*-
查詢和更新都正常了,但是項目不是 utf-8 的了。
# -*- coding: cp936 -*-
import pymssql
conn = pymssql.connect(host='192.168.10.167', user='sa', password='sa', database='Test')
cur = conn.cursor()
cmd = "INSERT INTO Demo VALUES('索引測試')";
print cmd
cur.execute(cmd)
conn.commit()
conn.close()