We'll explore how Python can interact with databases. We'll cover everything from basic database concepts to advanced database operations using Python. By the end of this topic, you'll have a thorough understanding of how to work with databases in Python, from establishing connections to executing queries and performing data manipulation.
A database is a structured collection of data that is organized and stored for easy access, retrieval, and management. It provides a systematic way of managing and storing data efficiently.
To interact with databases in Python, we need to establish a connection using appropriate database drivers.
import mysql.connector
# Establish connection
conn = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="mydatabase"
)
# Check if connection is successful
if conn.is_connected():
print("Connected to MySQL database")
else:
print("Failed to connect")
mysql.connector
module to connect to a MySQL database.Once connected, we can execute SQL queries to retrieve, insert, update, or delete data from the database.
# Create cursor
cursor = conn.cursor()
# Execute query
cursor.execute("SELECT * FROM users")
# Fetch and print results
for row in cursor.fetchall():
print(row)
# Close cursor
cursor.close()
We can use SQL INSERT
statements to add new records to a database table.
# Create cursor
cursor = conn.cursor()
# Execute INSERT query
cursor.execute("INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com')")
# Commit changes
conn.commit()
# Close cursor
cursor.close()
INSERT
query to add a new record to the “users” table with the specified name and email.conn.commit()
to make them permanent.We can use SQL UPDATE
statements to modify existing records in a database table.
# Create cursor
cursor = conn.cursor()
# Execute UPDATE query
cursor.execute("UPDATE users SET email = 'johndoe@example.com' WHERE name = 'John Doe'")
# Commit changes
conn.commit()
# Close cursor
cursor.close()
UPDATE
query to change the email address of a user named “John Doe” in the “users” table.We can use SQL DELETE
statements to remove records from a database table.
# Create cursor
cursor = conn.cursor()
# Execute DELETE query
cursor.execute("DELETE FROM users WHERE name = 'John Doe'")
# Commit changes
conn.commit()
# Close cursor
cursor.close()
DELETE
query to remove the user named “John Doe” from the “users” table.Transactions allow us to execute a sequence of SQL statements as a single unit of work. This ensures data consistency and integrity.
try:
# Start transaction
conn.start_transaction()
# Execute multiple SQL statements
cursor.execute("UPDATE users SET status = 'active' WHERE id = 1")
cursor.execute("INSERT INTO logs (user_id, action) VALUES (1, 'Updated status')")
# Commit transaction
conn.commit()
except mysql.connector.Error as e:
# Rollback transaction if an error occurs
conn.rollback()
print("Transaction failed:", e)
finally:
# Close cursor
cursor.close()
conn.start_transaction()
.conn.rollback()
.MySQL is a popular open-source relational database management system (RDBMS) known for its reliability, scalability, and ease of use.
Before connecting Python to MySQL, you need to install the MySQL Connector module using pip:
pip install mysql-connector-python
import mysql.connector
# Establish connection
conn = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="mydatabase"
)
# Check if connection is successful
if conn.is_connected():
print("Connected to MySQL database")
else:
print("Failed to connect")
mysql.connector
module to work with MySQL databases.SQLite is a lightweight, serverless, self-contained SQL database engine. It’s widely used in embedded systems and mobile applications.
SQLite comes pre-installed with Python, so you don’t need to install any additional modules.
import sqlite3
# Establish connection
conn = sqlite3.connect("mydatabase.db")
# Check if connection is successful
if conn:
print("Connected to SQLite database")
else:
print("Failed to connect")
sqlite3
module to work with SQLite databases.We've covered the basics of working with databases in Python. We learned how to establish connections to databases, execute SQL queries, perform data manipulation operations such as insertion, updating, and deletion, and handle advanced database operations including transactions.
Understanding how to interact with databases in Python is essential for building data-driven applications and performing data analysis tasks. With the knowledge gained from this topic, you'll be well-equipped to work with various types of databases and leverage the power of Python for managing and manipulating data effectively. Happy Coding!❤️