![]() |
VOOZH | about |
An SQLite database can be connected to a Python program using the sqlite3.connect() method. It establishes a connection by opening the specified database file and creates the file if it does not already exist.
To interact with an SQLite database, we first need to establish a connection to it using the connect() method. If the specified database file doesn't exist, SQLite will create it automatically.
sqliteConnection = sqlite3.connect('database_name.db')
After establishing the connection, we need to create a cursor object to execute SQL queries on the database.
cursor = sqliteConnection.cursor()
SQL query to be executed can be written in form of a string, and then executed using the cursor.execute() method. and the results can be fetched from the server by using the fetchall() method.
query = 'SQL query;'
cursor.execute(query)
result = cursor.fetchall()print('SQLite Version is {}'.format(result))
Below is an example that connects to an SQLite database, runs a simple query to retrieve the version of SQLite, and handles any potential errors during the process.
Output
Explanation: