0

am new to python programming and am currently learning about asynchronus programming using asyncio. I used asyncio to asynchronously read data from a sql server database , and it works fine. My problem is while i was learning to do this i came across a python library called "aioodbc" which states that ***"aioodbc is Python 3.5+ module that makes possible accessing ODBC_ databases with asyncio."


But am able to this fairly easily with the asyncio library and pyodbc ? so why should one use aioodbc over pyodbc and asyncio ? am i missing something here ?

ive attached the code ive used to test this out below , any feedback on this would be much appreciated

import asyncio
import pyodbc
import pandas as pd





def db_connection():
    # await asyncio.sleep(10)
    conn =  pyodbc.connect(
    Trusted_Connection = "Yes",
    Driver = '{ODBC Driver 18 for SQL Server}',
    Server ="My_db_server",
    Database  = "test_database",
    Encrypt="no"
        )
       
    # cursor = conn.cursor()
    return conn
    

async def table_one(conn):
    await asyncio.sleep(12)
    sql_query_string = "SELECT * FROM test_database.dbo.Employee;"
    df = pd.read_sql_query( sql_query_string, conn)
    print(df)
    
async def table_two(conn):
    
    sql_query_string = "SELECT * FROM test_database.dbo.Department;"
    df = pd.read_sql_query( sql_query_string, conn)
    print(df)

async def dummy():
    print("this is the dummy function")
    
async def main():
    conn = db_connection()
    task1 = asyncio.create_task(table_one(conn))
    task2 = asyncio.create_task(table_two(conn))
    task3 = asyncio.create_task(dummy())
    print("calling database connection")
    
    
    await task2
    await task1
    await task3
    


asyncio.run(main())

Note : i know that adding await infront pyodbc.connect() would result in an error because its not a asynchronous function but i can easily await the db_connection() function in my main function to get the same asynchronous functionality.

  • Well, it's a different ways of doing this, aioodbc enables native asyncronicity for the odbc methods. Your way means you have to wrap calls in methods which might get annoying after a while – siggemannen Jun 04 '23 at 18:20

0 Answers0