Python Language Sqlite3 Module Getting the values from the database and Error handling

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Fetching the values from the SQLite3 database.

Print row values returned by select query

import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute("SELECT * from table_name where id=cust_id")
for row in c:
    print row # will be a list

To fetch single matching fetchone() method

print c.fetchone()

For multiple rows use fetchall() method

a=c.fetchall() #which is similar to list(cursor) method used previously
for row in a:
    print row

Error handling can be done using sqlite3.Error built in function

try:
    #SQL Code
except sqlite3.Error as e:
    print "An error occurred:", e.args[0]


Got any Python Language Question?