Home > database >  Why in a simple loop I lose fetchAll's values of a sqlite3's table using python?
Why in a simple loop I lose fetchAll's values of a sqlite3's table using python?

Time:10-07

I need to print some rows from an sqlite3's table using python3, but into the loop I get none value. following my code:

import sqlite3
db=sqlite3.connect('db.db')
cdb=db.cursor()
cdb.execute('create table if not exists table1 (field1,field2,field3)')
cdb.execute('insert into table1 values (?,?,?)',(1,2,3))
db.commit()
cdb.execute('insert into table1 values (?,?,?)',(4,5,6))
db.commit()
cdb.execute('insert into table1 values (?,?,?)',(1,7,8))
db.commit()
cdb.execute('select * from table1')
for i in range(len(cdb.fetchall())):
    if cdb.fetchone()[0]==1:print(cdb.fetchone())
db.close()

my error message:
AttributeError: 'NoneType' object has no attribute 'replace'

Thanks

CodePudding user response:

Your call to cdb.fetchall() consumes the iterator and is pointless, so remove it:

for row in cdb.execute('select * from table1'):
    # do something with row

As described in the official documentation.

CodePudding user response:

After you fetchall the cursor point to nothing, so if you fetch anything it returns None.

to see what happend after commit the data just try:

cdb.execute('select * from table1')

print(cdb.fetchall()) # Return the data
print(cdb.fetchone()) # Return : None

db.close()

to fix this you could execute the sql again before the fetchone witch will be slow

I recommend doing this:

cdb.execute('select * from table1')

data = cdb.fetchall()
for i in data:
    if i[0] == 1: print(i)

db.close()
  • Related