Python Language Getting the values from the database and Error handling


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]