Python sqlite3 – Create Database Connection Object

Python – Create Database Connection in sqlite3

To create a connection object to sqlite, you can use sqlite3.connect() function.

In this tutorial, we shall learn the syntax of connect() function and how to establish a connection to an sqlite database, with the help of example programs.

Syntax – sqlite3.connect()

Following is the syntax of connect() function.

conn = sqlite3.connect('dbname.db')

where connect() function takes in a string for the database name and returns a sqlite3.Connection class object.

If the database is already present, it just returns a Connection object, else the database is created and then the Connection object to the newly created database is returned.

Example 1: Create a Connection Object using sqlite3

In this example, we will create a Connection object to the sqlite database named mysqlite.db.

Python Program

import sqlite3
conn = sqlite3.connect('mysqlite.db')

You have to import sqlite3 library before using any of its functions.

Example 2: Create a Connection Object to Database in memory using sqlite3

You can also create a database in memory (RAM). And for that, pass :memory: as argument to sqlite3.connect() while creating connection object.

Python Program

import sqlite3
conn = sqlite3.connect(':memory:')

Example 3: Use Connect Object to Get Cursor to the Database

To execute any operations on the sqlite database that you created, you have to create a cursor to the connection.

import sqlite3

conn = sqlite3.connect('mysqlite.db')
c = conn.cursor()

Summary

In this tutorial of Python Examples, we learned how to make a connection to sqlite database and create a cursor using the connection object.