Python SQLite
SQLite is a popular embedded database that is used in many applications. It is a database that is stored in a single file and is widely used in applications that require a light-weight, embedded database.
Syntax
The syntax to connect to a SQLite database in Python is as follows:
import sqlite3
# Connect to database
conn = sqlite3.connect('database_name.db')
# Create a cursor object
cursor = conn.cursor()
# Execute SQL query
cursor.execute('SELECT * FROM table_name')
# Fetch data from query
data = cursor.fetchall()
# Display data
for row in data:
print(row)
# Commit changes to database
conn.commit()
# Close connection
conn.close()
Example
Here is an example of creating a table and inserting data into the table using Python SQLite:
import sqlite3
# Connect to database
conn = sqlite3.connect('example.db')
# Create a cursor object
cursor = conn.cursor()
# Create a table
cursor.execute('''CREATE TABLE stocks
(date text, trans text, symbol text, qty real, price real)''')
# Insert data into table
cursor.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
# Commit changes to database
conn.commit()
# Query data from table
cursor.execute('SELECT * FROM stocks')
data = cursor.fetchall()
# Print data
for row in data:
print(row)
# Close connection
conn.close()
Output
The output of the above example will be:
('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14)
Explanation
The above example shows how to connect to a SQLite database in Python using the sqlite3
module. We create a cursor object that allows us to execute SQL queries against the database. We create a table called stocks
that has five columns. We then insert data into the table using the INSERT INTO
statement. Finally, we query the data from the table using the SELECT
statement and print the data to the console.
Use
Python SQLite is used to create, modify, and query data in a SQLite database. It is commonly used in web applications and mobile applications that require a light-weight, embedded database.
Important Points
- SQLite is a light-weight, embedded database that is stored in a single file.
- Python SQLite allows you to create, modify, and query data in a SQLite database.
- The
sqlite3
module in Python provides a way to connect to a SQLite database and execute SQL queries against it.
Summary
Python SQLite is a powerful tool for working with SQLite databases in Python. The sqlite3
module provides a simple way to connect to a database and execute SQL queries. With Python SQLite, you can create, modify, and query data in a SQLite database, making it a powerful tool for web applications and mobile applications.