I have a problem with my code, I have a database (aoidata.sqlite) and I want to print all rows where "comptype" (column) is one of the elements from my list.
Database:
Code:
import sqlite3
conn = sqlite3.connect('aoidata.sqlite')
c = conn.cursor()
listOfStatements = []
listID = [2, 3, 60]
rangeID = len(listID)
for i in range(rangeID):
c.execute("SELECT * FROM boardcomponents WHERE comptype=?", (listID[i],))
x = c.fetchone()
listOfStatements.append(x)
if x is not None:
x = c.fetchone()
listOfStatements.append(x)
else:
continue
conn.commit()
conn.close()`
Output:
(1, 'J4', 35.0, 180.0, 83.9999, 252.0, 0, 10.0, 10.0, 10.0, 4, 2)
(2, 'J3', 463.0, 351.0, 83.9999, 252.0, 2, 10.0, 10.0, 10.0, 4, 2)
(3, 'J6', 269.0, 480.0, 188.0, 141.0, 2, 10.0, 10.0, 10.0, 4, 3)
(195, 'T2_1', 1731.42, 711.765, 60.6912, 60.6912, 0, 50.0, 50.0, 10.0, 4, 60)
(196, 'T2_2', 2584.31, 700.237, 59.1059, 59.1059, 0, 50.0, 50.0, 10.0, 4, 60)
In my output I only get two rows were comptype
is 60, but in my database I have 8. What's wrong? How can I fix it?
The if
only fetches the second line and then it's done. You want to use a while
loop to fetch all the lines.
c.execute("SELECT * FROM boardcomponents WHERE comptype=?", (listID[i],))
x = c.fetchone()
while x:
listOfStatements.append(x)
x = c.fetchone()
As noted by @SergeBallesta, you don't have to do that, though; just use c.fetchall()
to fetch all the results.
Also notice that the SQL could be made a lot more efficient by querying for all the values at once.
SELECT * FROM boardcomponents WHERE comptype in (2, 3, 60);
You can build this query with something like
values = ', '.join(['?'] * len(listID))
c.execute("SELECT * FROM boardcomponents WHERE comptype in ({0})".format(values), listID)
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.