Using SQLite in Ironpython

SQLite is popular database engine which is very easy to use under python.Unfortunately it doesn’t work officially under ironpython as of now. In case of ironpython there is no official implementation from the ironpython team. But you don’t have to wait for the official fix. There is already one fix that lets you use SQLite under ironpython. Ironpython.SQlite project is a port of PySQLite and an unofficial attempt of managed SQLite3 module implementation using C#-SQLite library. In this post you’ll find out how to use SQLite in ironpython.

Setup

Step 1: You have to download IronPython.SQLite 2.6.1 from bitbucket. I assume you’re using ironpython version 2.7. You can download Ironpython.SQLite that works with previous version of ironpython (which is 2.6) if you want. Once you download and extract the zip file – you’ll find Ironpython.SQlite.dll file and SQLite folder.

Step 2: Go to your Ironpython installation and find “DLLs” folder. If you don’t have it then you’ll have to create it at root level. Once you create that folder just copy the ironpython.sqlite.dll file into this folder.

Step 3: Browse to the “Lib” folder in your ironpython installation. Once you navigate to this directory, just copy and paste
“sqlite3″ folder into this directory. You’re done.

Testing SQLite 3 Installation

Open command prompt and start the ironpython console. Type the following code into the ironpython console.

import sqlite3

If entering this piece of code doesn’t trigger error for you then installation is working fine.

Try SQLite Demo Code in Ironpython Console and see if it works for you.

import sqlite3
con=sqlite3.connect("test.db")
c=con.cursor()
c.execute('CREATE TABLE contacts(id INTEGER PRIMARY KEY, name VARCHAR(10))')
c.execute('INSERT INTO contacts VALUES (1,"mahesh")')
con.commit()
c.execute('SELECT * FROM contacts')
print c.fetchall()

You’ll see the output like this :

[(1, Mahesh)]

I have noticed that there are some errors during the installation.

Fix: If you’re having error at the first piece of code then chances are there you got “DLLs” directory issue. Make sure you type “DLLs” exactly during creation of folder and not “dlls”. If you copied the ironpython.sqlite.dll into “DLLs” folder correctly and still it shows error for you then try putting that .dll file in the root folder. If both these method don’t work for you then you should consider asking for help from maintainers of this .dll file.

I hope this tutorial helps. If you have any suggestions or need help with setup, feel free to post your comments.