简体   繁体   中英

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?

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.

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. Eg:

print(cursor.fetchall())

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