Skip to content
Related Articles

Related Articles

Python SQLite – Connecting to Database

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 16 May, 2021

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;'
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.



import sqlite3
    # 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();'
    # Fetch and output result
    result = cursor.fetchall()
    print('SQLite Version is {}'.format(result))
    # Close the cursor
# Handle errors
except sqlite3.Error as error:
    print('Error occured - ', error)
# Close DB Connection irrespective of success
# or failure
    if sqliteConnection:
        print('SQLite Connection closed')


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!