Search code examples
pythonpypyodbc

Python pypyodbc search value in Access database and select the field


I am using Python pypyodbc to connect to the Microsoft Access database.

I am able to connect to database as well.

Table name is "CODES" and looks like this :

Field1   Field2
U1A17    High Speed Link
U1A17    Low Speed Link

Now the value of dt_code = U1A17, which is present in Field1, search it in table and fetch the field2 respectively

dtc_code = dtc_designator + dtc_designator1 + dtc_designator2 + DTCLogged[loopindex+1]
print dtc_code

connection = pypyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb)};UID=admin;UserCommitSync=Yes;SafeTransactions=0;MaxScanRows=8;MaxBufferSize=2048;FIL={MS Access};DriverId=25;DefaultDir=C:\PYTHON27;DBQ=C:\PYTHON27\iso14229dtcs.mdb;')

cursor = connection.cursor()

cursor.execute("SELECT Field2 FROM DTC_CODES Where Field1 = 'dt_code'")

for row in cursor.fetchall():
    print row

Not able to fetch the value.


Solution

  • You are passing 'dt_code' string in the query instead of its value. You need to do something like this :

    Replace

    cursor.execute("SELECT Field2 FROM DTC_CODES Where Field1 = 'dt_code'")
    

    with

    cursor.execute("SELECT Field2 FROM DTC_CODES Where Field1 = ?", (dt_code,))