0

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

sorry always same error message
@Tommy in which line does the error occur?
@Tommy that code occurs neither in your question nor in my answer. Have you tried implementing my suggestion?
@Tommy and then what do you inside the for loop? A simple print(row) would be a starting point.
@Tommy glad to hear that! Please consider marking the answer as accepted and/or upvoting to complete the Q/A cycle.
|
1

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.