Python SQLite Connecting to Database (original) (raw)

Last Updated : 03 Feb, 2023

In this article, we’ll discuss how to connect to an SQLite Database using the sqlite3 module in Python.

Connecting to the Database

Connecting to the SQLite Database can be established using the connect() method, passing the name of the database to be accessed as a parameter. If that database does not exist, then it’ll be created.

sqliteConnection = sqlite3.connect('sql.db')

But what if you want to execute some queries after the connection is being made. For that, a cursor has to be created using the cursor() method on the connection instance, which will execute our SQL queries.

cursor = sqliteConnection.cursor() print('DB Init')

The SQL query to be executed can be written in form of a string, and then executed by calling the execute() method on the cursor object. Then, the result can be fetched from the server by using the fetchall() method, which in this case, is the SQLite Version Number.

query = 'SQL query;' cursor.execute(query) result = cursor.fetchall() print('SQLite Version is {}'.format(result))

Consider the below example where we will connect to an SQLite database and will run a simple query select sqlite_version(); to find the version of the SQLite we are using.

Example:

Python

import sqlite3

try :

`` sqliteConnection = sqlite3.connect( 'sql.db' )

`` cursor = sqliteConnection.cursor()

`` print ( 'DB Init' )

`` query = 'select sqlite_version();'

`` cursor.execute(query)

`` result = cursor.fetchall()

`` print ( 'SQLite Version is {}' . format (result))

`` cursor.close()

except sqlite3.Error as error:

`` print ( 'Error occurred - ' , error)

finally :

`` if sqliteConnection:

`` sqliteConnection.close()

`` print ( 'SQLite Connection closed' )

Output: