SQLite in Python: How to use the SQLite database in Python

Keywords: Python Database SQLite SQL

sqlite3 can integrate with Python using sqlite3 module. The sqlite3 module is written by Gerhard Haring. It provides a SQL interface compatible with the DB-API 2.0 specification described in PEP 249. You don't need to install the module separately, because the Python 2.5.x version or above defaults to have the module.

Use the "chinook" sample database database provided by sqlite tutorial, chinook.db, download address: https://www.sqlitetutorial.net/sqlite-sample-database/

At the same time, the ER-Diagram entity relation diagram of the database is provided, and some exercises can be done with 11 tables provided by the database.

 

import sqlite3

conn = sqlite3.connect('chinook.db')

cur = conn.cursor()

# treat the cursor object cur as an iterator
cur.execute('SELECT * from albums')

# call fetchone() method / or fetchall() method
print(cur.fetchone())

# iterating over each rows
for row in cur.execute('SELECT * from albums'):
    print(row)

cur.execute('SELECT * from customers')
print(cur.fetchone())

# add where clause 
ArtistId = ('272',)

# using ? is more secure than using %s
cur.execute('SELECT * from albums where ArtistId = ?',ArtistId)
print(cur.fetchall())

# using %s
ArtistId = ('272',)

# using ? is more secure than using %s
cur.execute('SELECT * from albums where ArtistId = %s' % ArtistId)
print(cur.fetchall())

cur.execute('SELECT * from artists')
print(cur.fetchall())

# insert value
cur.execute('INSERT OR REPLACE INTO artists values (276, "Jay Zhou")')
cur.execute('SELECT * from artists')
print(cur.fetchall())

# insert a list of records -- here we use executemany to insert another 3 singers
newArtists = [(278, 'Eason Chan'),
              (279, 'Yoga Lin'),
              (280, 'Jane Zhang'),]

# print(type(newArtists))
cur.executemany('INSERT OR IGNORE INTO artists values (? , ?)' , newArtists)
for row in cur.execute('SELECT * from artists'):
    print(row)

# using commit() to save those transactions / commiting those transations
conn.commit()
conn.close()

Posted by Kookedoh on Fri, 04 Oct 2019 20:43:11 -0700