This post describes how to connect to a SQLite database using Python.
CONNECTING TO SQLITE USING PYTHON
The sqlite3 module is part of Python’s standard library, and it have all of the futures you need to access and work with SQLite databases. You do not have to install any vendor-specific modules to work with SQLite in Python.
This code sample demonstrates how to connect to a SQLite database using the sqlite3 module and how to make some basic data manipulation:
#!/usr/bin/python from sqlite3 import connect # Replace username with your own A2 Hosting account username: conn = connect('/home/username/test.db') curs = conn.cursor() curs.execute("CREATE TABLE employees (firstname varchar(32), lastname varchar(32), title varchar(32));") curs.execute("INSERT INTO employees VALUES('Kelly', 'Koe', 'Engineer');") conn.commit() curs.execute("SELECT lastname FROM employees;") for (name) in curs.fetchall(): print name conn.close()
In the example above , we first create a Connection object that opens the SQLite database. If the test.db file already exists, Python opens that file. Otherwise, Python creates a new database in the test.db file.
Once we have a Connection object associated with the database, we can create a Cursor object. The Cursor object enables us to run the execute() method, which in turn enables us to run raw SQL statements (such as CREATE TABLE, SELECT, et cetera).
Finally, we call the close() method to close the connection to the database.