gpt4 book ai didi

Python3、pyodbc、SQL Server : Supplying Unicode and ANSI string as needed

转载 作者:太空宇宙 更新时间:2023-11-04 05:20:50 25 4
gpt4 key购买 nike

我使用 Python,目前使用 Python3,通过 ANSI char/varchar 列/索引访问遗留(读作“不会更改”)数据库。

我刚刚发现一个主要的性能问题(使用我完全控制的新数据库)通过将数据库转换为 nchar/nvarchar ( see this article ) 解决了,因此我的查询、列和索引都对齐到使用 Unicode。

这引出了一个问题,到目前为止我还无法用谷歌搜索它,我如何在 Python3 中给 pyodbc 一个非 Unicode 字符串,以便它正确地将字符串作为非 Unicode 字符串传递给 ODBC/SQL Server ?这对许多性能有重大影响,例如数据挖掘应用程序。

这似乎可行,但它正确吗?

conn = pyodbc.connect( connection_string )
curr = conn.cursor()
aString = 'Howdy!'
query = 'select * from aTable where aColumn = ?'
results = curr.execute( q, [aString.encode('ascii')] )

另外/另外,在 SQL Server 中的非 Unicode 列上构建 Unicode 索引是否更合适和/或可能? (我对数据库有足够的控制权来添加索引)。

最佳答案

is it correct?

根据 SQL Profiler 和 SQL Server Management Studio (SSMS) 在 Windows 下使用 SQL Server ODBC 进行测试时所说的内容,似乎是这样,假设字符串值确实将限制为 ASCII 字符。

如果我们只是传递 [aString] 作为查询参数,SQL Profiler 会显示 pyodbc 发送了这个

exec sp_prepexec @p1 output,N'@P1 nvarchar(6)',N'select * from aTable where aColumn = @P1',N'Howdy!'

如果我们要求 SSMS 向我们显示估计的执行计划

select * from aTable where aColumn = N'Howdy!'

它告诉我们它希望进行索引扫描。

但是,如果我们传递 [aString.encode('ascii')] 作为查询参数,SQL Profiler 显示 pyodbc 发送了这个

exec sp_prepexec @p1 output,N'@P1 varbinary(6)',N'select * from aTable where aColumn = @P1',0x486F77647921

如果我们要求 SSMS 向我们显示估计的执行计划

select * from aTable where aColumn = 0x486F77647921

它告诉我们它希望进行索引查找。

“搜索”通常比“扫描”更好,因此如果查询实际上返回正确的结果,我希望使用编码参数可以获得更好的性能。

关于Python3、pyodbc、SQL Server : Supplying Unicode and ANSI string as needed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40408205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com