要控制在从数据库服务器读取结果时如何将数据库类型映射到 Python 对象中,可以注册转换回调。
使用模块级的 register_converter 方法来注册回调。调用此方法时将以数据库类型为第一参数,以转换函数为第二参数。例如,要请求 sqlanydb 为任意列中描述为 DT_DECIMAL 类型的数据创建 Decimal 对象,可以使用下例:
import sqlanydb import decimal def convert_to_decimal(num): return decimal.Decimal(num) sqlanydb.register_converter(sqlanydb.DT_DECIMAL, convert_to_decimal) |
转换器可以注册为下列数据库类型:
DT_DATE DT_TIME DT_TIMESTAMP DT_VARCHAR DT_FIXCHAR DT_LONGVARCHAR DT_DOUBLE DT_FLOAT DT_DECIMAL DT_INT DT_SMALLINT DT_BINARY DT_LONGBINARY DT_TINYINT DT_BIGINT DT_UNSINT DT_UNSSMALLINT DT_UNSBIGINT DT_BIT |
下面的示例演示了如何截去小数位后的数字,将带小数的结果转换为整数。应用程序运行时显示的薪水金额是整数值。
import sqlanydb def convert_to_int(num): return int(float(num)) sqlanydb.register_converter(sqlanydb.DT_DECIMAL, convert_to_int) # Create a connection object, then use it to create a cursor con = sqlanydb.connect( userid="DBA", password="sql" ) cursor = con.cursor() # Execute a SQL string sql = "SELECT * FROM Employees WHERE EmployeeID=105" cursor.execute(sql) # Get a cursor description which contains column names desc = cursor.description print len(desc) # Fetch all results from the cursor into a sequence, # display the values as column name=value pairs, # and then close the connection rowset = cursor.fetchall() for row in rowset: for col in range(len(desc)): print "%s=%s" % (desc[col][0], row[col] ) print cursor.close() con.close() |
![]() |
使用DocCommentXchange讨论此页。
|
版权 © 2013, SAP 股份公司或其关联公司. - SAP Sybase SQL Anywhere 16.0 |