zillow / ctds

Python DB-API 2.0 library for MS SQL Server
MIT License
83 stars 12 forks source link

Bulk Insert without Context Manager #91

Open hub-il opened 3 years ago

hub-il commented 3 years ago

The bulk_insert command does not work if it is used without a context manager, returns a value for the number of rows that were supposed to be inserted and does not throw an error:

Works:

    with sql_cnxn as connection:
        return_result = connection.bulk_insert(table_name, bulk_insert_data)

Does not work:

return_result = sql_cnxn.bulk_insert(table_name, bulk_insert_data)
joshuahlang commented 3 years ago

Could you provide code to reproduce this error?

The following code works as expected without the context manager:

import pprint
import ctds

print('ctds version: ' + '.'.join(map(str, ctds.version_info)))
print('FreeTDS version: ' + ctds.freetds_version)

connection = ctds.connect(
    'localhost',
    user='SA',
    password='cTDS-unitest123'
)
with connection.cursor() as cursor:
    cursor.execute('SELECT @@VERSION')
    print(cursor.fetchone()[0])

    cursor.execute(
        '''
        DROP TABLE IF EXISTS RoundingTest
        '''
    )
    cursor.execute(
        '''
        CREATE TABLE RoundingTest(
            NumericColumn NUMERIC(8,2),
            NumericColumn2 NUMERIC(12,5)
        )
        '''
    )

connection.bulk_insert(
    'RoundingTest',
    [
        [77.4930] * 2,
        [339.6490] * 2,
    ]
)

with connection.cursor() as cursor:
    cursor.execute(
        '''
        SELECT * FROM RoundingTest
        '''
    )

    pprint.pprint(
        list(map(tuple, cursor.fetchall()))
    )