Click here to view and discuss this page in DocCommentXchange. In the future, you will be sent there automatically.

SAP Sybase SQL Anywhere 16.0 » SQL Anywhere サーバ プログラミング » Python サポート » sqlanydb を使用する Python スクリプト

 

データベースタイプの変換

データベースサーバから結果がフェッチされたときに、データベースタイプを Python オブジェクトにマッピングする方法を制御するには、変換コールバックを登録します。

コールバックの登録には、モジュールレベルの register_converter メソッドを使用できます。このメソッドは、データベースタイプを最初のパラメータ、変換関数を 2 番目のパラメータとして呼び出されます。たとえば、データ型 DT_DECIMAL として記述されるカラムのデータに対して Decimal オブジェクトを作成するよう sqlanydb に要求する場合は、次の例を使用します。

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()