Create Database Connection Object - Python sqlite3
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 of 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.
Examples
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.
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:')
3. Use connect o 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.