Open In App

Python SQLite – Connecting to Database

Last Updated : 03 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:
   
    # Connect to DB and create a cursor
    sqliteConnection = sqlite3.connect('sql.db')
    cursor = sqliteConnection.cursor()
    print('DB Init')
 
    # Write a query and execute it with cursor
    query = 'select sqlite_version();'
    cursor.execute(query)
 
    # Fetch and output result
    result = cursor.fetchall()
    print('SQLite Version is {}'.format(result))
 
    # Close the cursor
    cursor.close()
 
# Handle errors
except sqlite3.Error as error:
    print('Error occurred - ', error)
 
# Close DB Connection irrespective of success
# or failure
finally:
   
    if sqliteConnection:
        sqliteConnection.close()
        print('SQLite Connection closed')


Output:


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads