SQL 使用 pypyodbc 对列名称进行服务器编码

SQL Server encoding of column names with pypyodbc

我正在尝试使用 pypyodbc 将 Python 连接到 SQL 服务器数据库。当我获得 cursor.description 以获取 table 的列名时,我得到以下信息:

u'\u6573\u7373\u6f69\u496ed' but I have this string in SQL Server: sessionId
u'\u6163\u6c6ce\u496ed' but I have this string in SQL Server: calle
u'\u6974\u656d\u7473\u6d61p' but I have this string in SQL Server: timestamp
u'\u6576\u7372\u6f69np' but I have this string in SQL Server: version

sessionId、calle、timestamp 和version 是SQL 服务器table 的列名。

我从 cursor.descriptions 得到的字符串是剩下的。

我要转换字符串 u'\u6573\u7373\u6f69\u496ed' 到字符串 sessionId 中,与其余列相同。

我该怎么做?

提前致谢!

我使用这段代码得到了这些结果:

cursor = conexion_sql.conn.cursor()
cursor.execute('select top 5 * from DWH.COB.table')

然后我得到描述:

cursor.description

我得到了这个:

[(u'\u6573\u7373\u6f69\u496ed', unicode, 37, 37L, 37L, 0, True),
 (u'\u6163\u6c6ce\u496ed', unicode, 4000, 4000L, 4000L, 0, True),
 (u'\u6974\u656d\u7473\u6d61p', datetime.datetime, 23, 23L, 23L, 3, False),
 (u'\u6576\u7372\u6f69np', unicode, 10, 10L, 10L, 0, True),
 (u'\u6546\u6863\u4361\u7261\u6167\u445f\u4857',
  datetime.datetime,
  23,
  23L,
  23L,
  3,
  False),
 (u'\u6946\u6863\u7265\u436f\u7261\u6167\u445f\u4857',
  unicode,
  100,
  100L,
  100L,
  0,
  False)]

详情:

Python version: 2.7.13
pypyodbc version: 1.3.4
ODBC Driver: ODBC Driver 17 for SQL Server


conn_string = '''
        DRIVER={4};
        SERVER={0};
        DATABASE={1};
        UID={2};
        PWD={3};
        TrustServerCertificate=yes;
        Connection Timeout=15
        '''.format(server, database, uid, pwd, driver)
        self.conn = pypyodbc.connect(conn_string)

我能够重现您的问题:

# -*- coding: utf-8 -*-
import sys

import pypyodbc

print(sys.version.replace('\n', ''))
# 2.7.15+ (default, Oct  7 2019, 17:39:04) [GCC 7.4.0]
print(pypyodbc.version)
# 1.3.5

connection_string = (
    'DRIVER=ODBC Driver 17 for SQL Server;'
    'SERVER=192.168.0.179,49242;'
    'DATABASE=myDb;'
    'UID=sa;PWD=_whatever_;'
)
cnxn = pypyodbc.connect(connection_string)
crsr = cnxn.cursor()
crsr.execute("SELECT 1 AS foo")
desc = crsr.description
col_name = desc[0][0]
print(col_name)  # 潦o
print(repr(col_name))  # u'\u6f66o'

pypyodbc 不再被维护。请改用 pyodbc