sqlite3 (1) – Programming in an object-oriented style

SQLite is a C library that provides a lightweight disk-based database that doesn’t require a separate server process and allows accessing the database using a nonstandard variant of the SQL query language. sqlite3 is a Python package that provides a SQL interface.

To program in an object-oriented style:

import sqlite3

class Database:
    def __init__(self,db):
        """
        Connect to database or create a database if not exists.
        db: database file name.
        """
        self.conn = sqlite3.connect(db)
        self.cursor = self.conn.cursor()

    def __del__(self):
        """
        Close connection to database.
        """
        self.conn.close()

    def dbcommit(self):
        """
        Write changes to database.
        """
        self.conn.commit()

When an object is instantiated, it is connected to the database. db is the database file name, such as “stock_quotes.db”. If the file does not exist, a new database file will be created.

GitHub: https://github.com/DropletX/sqlite3/blob/master/sqlite3_1.py

Reference:

1) sqlite3 — DB-API 2.0 interface for SQLite databases

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s