This article describes steps to connect to SQLite using Python.
Getting connect to SQLite using Python :
The sqlite3 module is a part of Python’s standard library which includes all the functionalities that you need to access and work with SQLite databases. To work with SQLite in Python, you don’t have to install any vendor-specific modules.
The following code demonstrates how you can connect to a SQLite database using the sqlite3 module and how you can do some basic manipulations :
#!/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('Courtney', 'Kem', 'Engineer');") conn.commit() curs.execute("SELECT lastname FROM employees;") for (name) in curs.fetchall(): print name conn.close()
In this example shown, we have first created a Connection object that will open SQLite database. In case the test.db file exists already, Python will open that file. Otherwise, Python will create a new database in the test.db.
Once we get a Connection object associated with the database, next we can create a Cursor object. The Cursor object allows us to run the execute() method, which then allows us to run raw SQL statements (like CREATE TABLE, SELECT, etc).
At-last, we can call the close() method in-order to close the connection to the database.
For more information about sqlite3 method, visit this :
Also Read :