In this lesson we want to learn How to Connect Python with SQLite Database.
What is SQLite ?
SQLite is software library that provides relational database management system. it is lightweight database that can be easily embedded into applications and this feature makes it popular choice for applications that needs database, but don’t require the full functionality of traditional relational database management system.
SQLite is file based which means that database is stored in single file on disk. This makes it easy to transfer the database between systems, and eliminates the need for separate server process to manage the database. also SQLite supports standard SQL (Structured Query Language) and can be accessed using a variety of programming languages, including Python, C, Java and many others.
SQLite is ACID (Atomicity, Consistency, Isolation, Durability) compliant which means that it provides robust transactional support and ensures data integrity and consistency, even in the face of software crashes, power failures and other unexpected events. also SQLite is fast and efficient and it is good choice for applications that require high performance and low overhead.
How to Connect Python with SQLite Database ?
For connecting SQLite database in Python, you can use the sqlite3 module. this is an example of how you can use this module to interact with SQLite database in Python:
# Connect to database creates the database file if it doesn't exist
conn = sqlite3.connect('example.db')
# Create cursor to execute SQL commands
cursor = conn.cursor()
# Create table
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
# Insert data into table
cursor.execute("INSERT INTO users (name, email) VALUES ('John Doe', 'email@example.com')")
# Commit the changes to the database
# Query the data
cursor.execute("SELECT * FROM users")
# Fetch all the results
rows = cursor.fetchall()
# Print the results
for row in rows:
# Close the connection
In this example sqlite3 module is imported and a connection is established to SQLite database file named example.db. cursor is then created to execute SQL commands, and the table name is users that is created (if it doesn’t already exist), and data is inserted into the table. the changes are committed to the database, and the data is queried and printed. Finally, the connection is closed.