我正在使用 pyodbc 连接 sqlserver,下面是我的连接字符串。一切正常,但结果以 unicode 字符串形式返回。我在连接字符串中有 CHARSET=UTF8,但它仍然以 unicode 字符串形式返回?
有什么方法可以使用连接参数本身来限制它吗?
我不想调用额外的函数来将我的 unicode 转换为普通字符串。
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 属性,因此这对您没有任何好处。
您遇到的总体问题是数据库中的数据是 unicode。该列的数据类型是 nvarchar,它是一个扩展的(UTF-16...在 Windows 中可能是 UC-2,不记得了)数据类型以包含国际数据字符。
您的选择是在选择查询中通过强制转换转换数据,例如:
SELECT CAST(fieldname AS VARCHAR) AS fieldname
或者用python转换,例如:
# 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 中。
关于python - pyodbc 删除 unicode 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16565028/