Newbie101
Newbie101

Reputation: 501

How to print data from sqlite3 database?

I don't understand how I would print the data that I have queried from a database.

For example:

def display_stock(self):
    with sqlite3.connect("db_name.db") as db:
        cursor = db.cursor()
        sql = "SELECT Name FROM Product WHERE StockLevel > 0"
        cursor.execute(sql)
        db.commit()

So I created this function to select all products in a database that are still in stock. But how do I display these products in the database to the user?

Upvotes: 2

Views: 9763

Answers (2)

Mureinik
Mureinik

Reputation: 311338

Once you've executed a query, you need to fetch the result. Either with fetchone (fetches one result row), fetchmany (fetches multiple rows) or fetchall fetches all of them. E.g.:

print(cursor.fetchall())

Upvotes: 2

Wes Doyle
Wes Doyle

Reputation: 2287

You can treat the cursor as an iterator, or get results from the cursor using fetchone() or fetchall()

ie:

print(cursor.fetchone())

If you are only executing a SELECT statement, you don't need to commit.

Upvotes: 1

Related Questions