简体   繁体   中英

Python Access odbc and should skip the row

I am using MS Access to import the table information. Table is below:

Field1   Field2
U1a14    High Speed Link
U0001    Medium speed data
U0022    Low Speed Link 

My code value is like: code = U1a14 code = U0001 code = B11DB (This code is not present in table)

I am connecting to odbc and searching for code in table.

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;')
cursor1 = connection.cursor()
cursor1.execute("SELECT Field2 FROM Table Where Field1 = '{}'".format(code))

for row in cursor1.fetchone():
  print row

I am getting error:

error:
for row in cursor1.fetchone():
TypeError: 'NoneType' object is not iterable

How Can I fix it, If the code is not present in my Table, it should skip and print only existing row

Change the code to the following, check cursor1.fetchone() is not NULL.

    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;')
    cursor1 = connection.cursor()
    cursor1.execute("SELECT Field2 FROM Table Where Field1 = '{}'".format(code))
    row = cursor1.fetchone()
    while row is not None:
        print row[0], row[1]
        row = cursor1.fetchone()
    cursor1.close()
    connection.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM