Python - Databases

From XennisWiki
Jump to: navigation, search

SQLite

Further information: sqlite3 - DB-API 2.0 interface for SQLite databases

Install the module: sqlite3

Basic usage

import sqlite3 as lite
con = None
try:
    con = lite.connect(os.path.join(BASE_DIR, 'db.sqlite3'), isolation_level=None)
    cur = con.cursor()
    cur.execute("INSERT INTO authors VALUES (?, ?)", (2031, 'Tolkien') )
except lite.Error, e:
    print('Error %s:' % e.args[0])
    sys.exit(1)
finally:
     if con:
         con.close(python)

Usage of the methods executescript and executemany

cur.executescript('SQL-HERE')

authors = (
    (1, 'Tolkien'),
    (2, 'Lessing'),
    (3, 'Schiller')
)
cur.executemany("INSERT INTO authors VALUES(?, ?)", authors)

PostgreSQL (psycopg2)

Further information: Using psycopg2 with PostgreSQL

Install the module: psycopg2

Basic usage

import psycopg2

conn = psycopg2.connect(host='HOST',
                        dbname='NAME',
                        user='USER',
                        password='PASSWORD')
cur = conn.cursor()
cur.execute("INSERT INTO authors (id, name) VALUES (%s, %s)", (1, 'Tolkien'))
conn.commit()

See also