pyodbc 删除 unicode 字符串 [英] pyodbc remove unicode strings
问题描述
我正在使用 pyodbc 连接 sqlserver,下面是我的连接字符串..一切正常,但结果作为 unicode 字符串返回..我在连接字符串中有 CHARSET=UTF8 但它仍然作为 unicode 字符串返回?
I'm using pyodbc to connect sqlserver and below is my connection string..Everything is proper but the results are returned as a unicode string..I have the CHARSET=UTF8 in the connection string but still its returning as unicode string?
有什么办法可以使用连接参数本身来限制它吗?
Is there any way that I can limit it using the connection paramter itself?
我不想调用额外的函数来将我的 unicode 转换为普通字符串.
I don't want to call a extra function to convert my unicode to normal strings.
import pyodbc as p
connstr= 'DRIVER={SQL Server};SERVER=USERNAME\SQLEXPRESS;DATABASE=TEST;Trusted_Connection=yes;unicode_results=True;CHARSET=UTF8'
conn = p.connect(connstr)
print conn
cursor = conn.cursor()
result = cursor.execute("select * from employee1")
for each in result:
print each
推荐答案
您无法在连接字符串中处理此问题.SQL Server 在其 odbc 连接设置中没有 CHARSET 属性,因此这对您没有任何好处.
You can not handle this issue in the connection string. SQL Server doesn't have a CHARSET property in it's odbc connection settings, so that won't do you any good.
您遇到的总体问题是数据库中的数据是 unicode.该列的数据类型是 nvarchar,它是包含国际数据字符的扩展(UTF-16...在 windows 中可能是 UC-2,记不清了)数据类型.
The overall issue you are having is that the data IS unicode in the database. The data type for that column is nvarchar, it is an extended (UTF-16... could be UC-2 in windows, can't remember) data type to include international data characters.
您的选择是通过选择查询中的强制转换来转换数据,例如:
Your options are to convert the data via cast in the select query, e.g.:
SELECT CAST(fieldname AS VARCHAR) AS fieldname
或在python中转换,例如:
or convert it in python, e.g.:
# to utf-8
row.fieldname.encode('utf8')
# to ascii, ignore non-utf-8 characters
row.fieldname.encode('ascii', 'ignore')
# to ascii, replace non-utf-8 characters with ?
row.fieldname.encode('ascii', 'replace')
如果您不需要国际字符,那么您可以将数据存储在 varchar 而不是 nvarchar 中.
If you don't need international characters, then you could store the data in varchar instead of nvarchar.
这篇关于pyodbc 删除 unicode 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!