Welcome to our comprehensive Python Database tutorial! In this lesson, we'll dive into the world of databases, exploring why they're essential, and learn how to interact with them using Python.
By the end of this tutorial, you'll be able to create, read, update, and delete (CRUD) data in a database, making you ready to handle real-world projects.
A database is a structured collection of data. It allows you to store, manage, and retrieve data efficiently. Databases are crucial for applications that need to store large amounts of data and perform complex queries.
Python, combined with a database, can help you build powerful applications. Here are some reasons why:
SQLite is a lightweight, self-contained database engine that's perfect for beginners. It doesn't require a separate server and works seamlessly with Python.
Let's create our first SQLite database using Python:
import sqlite3
conn = sqlite3.connect('my_database.db') # Create a connection
cursor = conn.cursor() # Create a cursor object
# Create a table named 'users'
cursor.execute('''CREATE TABLE users
(id INTEGER PRIMARY KEY,
firstname TEXT,
lastname TEXT,
email TEXT)''')
conn.commit() # Save changes
conn.close() # Close the connectionš” Pro Tip: conn.commit() saves the changes you've made to the database. Remember to call this function when you're done.
Now, let's insert some data into our 'users' table:
import sqlite3
conn = sqlite3.connect('my_database.db')
cursor = conn.cursor()
# Insert a user
cursor.execute("INSERT INTO users VALUES (1, 'John', 'Doe', 'john.doe@example.com')")
conn.commit()
conn.close()To retrieve the data we've inserted, we'll use the cursor.execute() function again, but this time with a SELECT statement:
import sqlite3
conn = sqlite3.connect('my_database.db')
cursor = conn.cursor()
# Query all users
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
print(row)
conn.close()Updating and deleting data is just as simple:
# Update a user's email
conn = sqlite3.connect('my_database.db')
cursor = conn.cursor()
cursor.execute("UPDATE users SET email='john_doe@example.com' WHERE id=1")
conn.commit()
conn.close()
# Delete a user
conn = sqlite3.connect('my_database.db')
cursor = conn.cursor()
cursor.execute("DELETE FROM users WHERE id=1")
conn.commit()
conn.close()What does the `conn.commit()` function do in Python database operations?
That's it for our Python Database Introduction! In the next lessons, we'll dive deeper into more complex topics, like working with multiple tables, handling errors, and optimizing performance. Happy coding! š