下面是調用方式:
Example script - pymssql module (DB API 2.0)
Example script - _mssql module (lower level DB access)
不過,在我使用過程中,發現,如果表中包含了ntext欄位,就會出錯,提示
不能用 DB-Library(如 ISQL)或 ODBC 3.7 或更早版本將 ntext 資料或僅使用
Unicode定序的 Unicode 資料發送到用戶端。
查了一下,發現官方網站有解釋:
Q: What means "Unicode data in a Unicode-only collation or ntext data cannot be sent to clients using DB-Library"?
A: If you connect to a SQL Server 2000 SP4 or SQL Server 2005, and if you make a SELECT query on a table that contains a column of type NTEXT, you may encounter the following error:
_mssql.error: SQL Server message 4004, severity 16, state 1, line 1:
Unicode data in a Unicode-only collation or ntext data cannot be sent to clients using DB-Library (such as ISQL) or ODBC version 3.7 or earlier.
It's the SQL Server complaining that it doesn't support pure Unicode via TDS or older versions of ODBC. There's no fix for this error. Microsoft has deprecated DB-Library a long ago, in favor of ODBC, OLE DB, or SQL Native Client. Many new features of SQL 2005 aren't accessible via DB-Library so if you need them, you have to switch away from pymssql or other tools based on TDS and DB-Library.
A workaround is to change the column type to NVARCHAR (it doesn't exhibit this behaviour), or TEXT.
大概意思是,這是因為我們的pymssql使用早期的ODBC函數集來擷取資料。後來微軟才引入了ntext和nvarchar類型,但Microsoft並沒有更新他們的 C-library,所以就沒辦法支援了。建議:將ntext修改為nvarchar或text.
顯然,這不是個好的解決方案,那麼是否就沒有其他辦法了呢?
還好,不用絕望,既然不支援ntext但支援text,那麼我們只需要在輸出時將ntext轉換為text就好了,方法很簡單:
SELECT cast ( field_name AS TEXT ) AS field_name
唯一的問題,可能是ntext和text欄位所支援的長度不一樣,所以也許你還需要設定一下TEXTSIZE
SET TEXTSIZE 65536
當然,你還可以將欄位設定的大一點,這個就看你的需要了。