Python SQLite Tutorial

There are various SQLite wrappers available using which you can interact with SQLite3 database. But the most popular one is PySQLite. There is no need to install PySQLite because it comes as a standard module from Python 2.5 onwards. In your coding, you have to import sqlite3 module to work with SQLite3.

Steps to connect to SQLite database in Python

  1. Before you interact with SQLite, you have to import sqlite3 module.
    import sqlite3
  2. Create a connection to a database by providing a filename. If the database does not exist then it will be created. connect() function is used to connect to a database.
    conn = sqlite3.connect('databasename.db')
  3. Get a cursor from the connection by calling cursor() function.
    cur = conn.cursor()
  4. Execute SQL query using execute() function.
  5. If you have made changes to the database then you must call commit() function so that changes are saved back to the file.
    conn.commit()
  6. Call close() function to close the connection.
    conn.close()

Following are the topics that are covered in Python SQLite tutorial-