I needed this for a small script I was doing and it turns out it's very easy.
Monday, May 25, 2009
Tuesday, May 5, 2009
Sqlite is an embedded database engine that has bindings in a lot of popular programming languages (Perl, C++ and most notably Python). Sqlite3 is part of the standard Python library so there's no need to muck about with installation.
Here's my mini tutorial to using sqlite3 in Python:
1. First thing you have to do is import the module so:
2. Next is to connect to a 'database' which is in reality a single file in the filesystem. Note that this will be created in the working directory of your current process (in this case the Python interpreter). Let's use an absolute path to make it clear:
conn = sqlite3.connect( '/yourpath/exampledb' )
3. Once you have a connection, you probably will create a cursor. You need a cursor object to use its execute method to perform SQL commands:
cur = conn.cursor()
4. Run your SQL commands. Note that like most database engines, sqlite3 supports its particular dialect of SQL. Check it out here: SQL As Understood by SQLite.
Here are some examples:
- to create a table:
cur.execute( '''CREATE TABLE books (title text, author text)''' )
- to insert a row of data:
cur.execute( '''INSERT INTO books VALUES ('Judas Unchained', 'Hamilton, Peter' )''' )
5. Most importantly, to save your data, issue the following command:
6. To close the database:
That's it! :)
Here are some more Python links:
- Update: I have another related article: Python/Sqlite trick tidbit.
- A python dictionary technique/hack
Here are some online docs:
Python docs for the sqlite3 Python bindings: DB-API 2.0 interface for SQLite databases
SQLite homepage is here.