Showing posts with label Python database. Show all posts
Showing posts with label Python database. Show all posts

Transactions and Rollbacks in SQL: Beginner-Friendly SQLite & Python Tutorial

Transactions and Rollbacks with SQL: A Simple and Fun Tutorial for Everyone

Welcome back to our magical SQL journey! In our previous tutorials, we learned how to manage data in a database using commands like INSERT, SELECT, and JOIN, and we connected tables in our toy store database. Now, let’s explore a super important concept: transactions and rollbacks. These are like a safety net for your database, ensuring your changes are saved only when you’re sure everything is perfect. We’ll use SQLite and Python with our toystore.db database, keeping it fun and simple like organizing a toy store with a magical undo button!


What are Transactions and Rollbacks?

Imagine you’re building a toy castle with blocks. You carefully add blocks one by one, but if one step goes wrong (like a block falls), you want to undo everything and start over to keep the castle perfect. In a database, a transaction is like a group of changes (like adding or updating data) that you want to happen all at once—or not at all. A rollback is like your undo button, letting you cancel those changes if something goes wrong.

For example, in our toy store, if a customer buys two toys, you need to update the toy inventory and record the sale. A transaction ensures both steps happen together, or neither happens if there’s a mistake. This keeps your database safe and accurate!


Why Learn Transactions and Rollbacks?

  • They’re Safe: They protect your data from mistakes, like saving only half a sale.
  • They’re Simple: Just a few commands make your database super reliable.
  • They’re Useful: They’re used in apps, websites, and games to ensure data stays correct.
  • They’re Fun: It’s like having a magic undo button for your database!
  • They Build on SQL: If you know INSERT or UPDATE from our earlier tutorials, you’re ready to learn this.

Let’s dive into our toy store and learn how to use transactions and rollbacks!


Getting Started

We’ll use Python with SQLite to run our SQL commands, just like before. Make sure you have Python installed (download it from python.org if needed). SQLite comes with Python, so no extra setup is required. You can also use DB Browser for SQLite to see your data visually, but we’ll focus on Python code for clarity.

We’ll work with our toystore.db database, using the Toys table and a new Sales table to track toy purchases. Here’s the setup code to create these tables and add some sample data:

import sqlite3

# Connect to the database
conn = sqlite3.connect('toystore.db')
cursor = conn.cursor()

# Create Toys table
cursor.execute('''
    CREATE TABLE IF NOT EXISTS Toys (
        ToyID INTEGER PRIMARY KEY,
        Name TEXT,
        Type TEXT,
        Price REAL,
        Stock INTEGER
    )
''')

# Create Sales table
cursor.execute('''
    CREATE TABLE IF NOT EXISTS Sales (
        SaleID INTEGER PRIMARY KEY,
        ToyID INTEGER,
        Quantity INTEGER,
        TotalPrice REAL,
        FOREIGN KEY (ToyID) REFERENCES Toys(ToyID)
    )
''')

# Clear existing data to avoid duplicates
cursor.execute("DELETE FROM Toys")
cursor.execute("DELETE FROM Sales")

# Add toys
cursor.execute("INSERT INTO Toys (Name, Type, Price, Stock) VALUES ('Robot', 'Action Figure', 30.00, 10)")
cursor.execute("INSERT INTO Toys (Name, Type, Price, Stock) VALUES ('Jigsaw', 'Puzzle', 10.00, 15)")
cursor.execute("INSERT INTO Toys (Name, Type, Price, Stock) VALUES ('Teddy', 'Stuffed Animal', 15.00, 8)")

conn.commit()
conn.close()
print("Toy store database ready for transactions!")

What’s Happening?

  • Toys table: Stores toy details with a new Stock column.
  • Sales table: Records sales with ToyID, Quantity, and TotalPrice.
  • FOREIGN KEY: Ensures data integrity by linking toys to sales.
  • We added 3 toys with different stock levels.

Toys:

ToyIDNameTypePriceStock
1RobotAction Figure30.0010
2JigsawPuzzle10.0015
3TeddyStuffed Animal15.008

What is a Transaction?

A transaction is a group of SQL commands that must all succeed together or not happen at all. It follows the ACID properties:

  • Atomicity: All commands happen as one unit (all or nothing).
  • Consistency: The database stays valid (e.g., stock doesn’t go negative).
  • Isolation: Transactions don’t mess with each other.
  • Durability: Saved changes stay saved, even if the computer crashes.

SQL Transaction Commands

  • BEGIN TRANSACTION: Starts a transaction.
  • COMMIT: Saves all changes.
  • ROLLBACK: Cancels all changes if something fails.

In Python with SQLite, you can use conn.commit() and conn.rollback().


Example 1: A Successful Transaction

import sqlite3

conn = sqlite3.connect('toystore.db')
cursor = conn.cursor()

try:
    cursor.execute("UPDATE Toys SET Stock = Stock - 2 WHERE ToyID = 1")
    cursor.execute("INSERT INTO Sales (ToyID, Quantity, TotalPrice) VALUES (1, 2, 60.00)")
    
    conn.commit()
    print("Sale of 2 Robots completed successfully!")
    
    cursor.execute("SELECT * FROM Toys WHERE ToyID = 1")
    print("Robot Stock:", cursor.fetchone())
    cursor.execute("SELECT * FROM Sales")
    print("Sales:", cursor.fetchall())

except:
    conn.rollback()
    print("Something went wrong, changes undone!")

conn.close()

What’s Happening?

  • try: Handles errors.
  • UPDATE: Reduces Robot stock.
  • INSERT: Adds the sale.
  • commit(): Saves if successful.
  • rollback(): Undoes if an error happens.
Sale of 2 Robots completed successfully!
Robot Stock: (1, 'Robot', 'Action Figure', 30.0, 8)
Sales: [(1, 1, 2, 60.0)]

Example 2: Rolling Back a Failed Transaction

import sqlite3

conn = sqlite3.connect('toystore.db')
cursor = conn.cursor()

try:
    cursor.execute("SELECT Stock FROM Toys WHERE ToyID = 2")
    stock = cursor.fetchone()[0]
    
    if stock < 20:
        raise Exception("Not enough Jigsaws in stock!")
    
    cursor.execute("UPDATE Toys SET Stock = Stock - 20 WHERE ToyID = 2")
    cursor.execute("INSERT INTO Sales (ToyID, Quantity, TotalPrice) VALUES (2, 20, 200.00)")
    
    conn.commit()
    print("Sale completed!")

except Exception as e:
    conn.rollback()
    print(f"Error: {e}. Changes undone!")

cursor.execute("SELECT * FROM Toys WHERE ToyID = 2")
print("Jigsaw Stock:", cursor.fetchone())
cursor.execute("SELECT * FROM Sales WHERE ToyID = 2")
print("Jigsaw Sales:", cursor.fetchall())

conn.close()
Error: Not enough Jigsaws in stock!. Changes undone!
Jigsaw Stock: (2, 'Jigsaw', 'Puzzle', 10.0, 15)
Jigsaw Sales: []

Example 3: Combining Transactions with Joins

First, create a Customers table:

conn = sqlite3.connect('toystore.db')
cursor = conn.cursor()

cursor.execute('''
    CREATE TABLE IF NOT EXISTS Customers (
        CustomerID INTEGER PRIMARY KEY,
        Name TEXT
    )
''')
cursor.execute("DELETE FROM Customers")
cursor.execute("INSERT INTO Customers (Name) VALUES ('Alice')")
conn.commit()
conn.close()

Now process a sale:

import sqlite3

conn = sqlite3.connect('toystore.db')
cursor = conn.cursor()

try:
    cursor.execute("UPDATE Toys SET Stock = Stock - 3 WHERE ToyID = 3")
    cursor.execute("INSERT INTO Sales (ToyID, Quantity, TotalPrice) VALUES (3, 3, 45.00)")
    
    conn.commit()
    print("Sale of 3 Teddies completed!")
    
    cursor.execute('''
        SELECT Customers.Name, Toys.Name, Toys.Stock
        FROM Sales
        INNER JOIN Toys ON Sales.ToyID = Toys.ToyID
        INNER JOIN Customers ON Customers.CustomerID = 1
        WHERE Sales.ToyID = 3
    ''')
    print("Sale Details:", cursor.fetchall())

except:
    conn.rollback()
    print("Sale failed, changes undone!")

conn.close()
Sale of 3 Teddies completed!
Sale Details: [('Alice', 'Teddy', 5)]

Tips for Success

  1. Use Transactions when multiple commands must go together.
  2. Check Conditions like stock before updating.
  3. Test Rollbacks using intentional errors.
  4. Write Clear Code for debugging and maintenance.
  5. Practice with your own mini projects!

Common Questions

1. Are transactions hard?

No! Think of them as grouped commands with undo.

2. Do transactions work in other databases?

Yes! PostgreSQL, MySQL, and others support them.

3. What happens if I forget to commit?

Changes may be lost. Always call commit() explicitly.

4. Can I rollback after commit?

No, you must start a new transaction to reverse a change.


Wrapping Up

Transactions and rollbacks in SQL are like a magical safety net, ensuring your database changes are all-or-nothing. In this tutorial, we used transactions to process toy sales, rolled back a failed sale, and combined transactions with joins in our toystore.db database. Whether you’re a beginner or an experienced coder, transactions are a fun and essential skill for keeping data safe.

Try creating your own database for something cool, like a game or library, and practice transactions. Use DB Browser for SQLite to see your data or keep coding in Python. With transactions and rollbacks, you’re now a database superhero, keeping your data safe and sound!

Happy SQL adventures, and keep your data secure!


SQLite Tutorial for Beginners: Create a Database and Tables with Python Step-by-Step

Creating a Database and Tables with SQLite: A Simple and Fun Tutorial for Everyone


Introduction

Imagine you’re building a magical toy box where you can neatly store all your toys, books, or even your favorite snacks, and find them whenever you want. In the world of computers, a database is like that magical toy box, and tables are the compartments inside it that keep everything organized. In this tutorial, we’ll learn how to create a database and tables using SQLite, a super simple and lightweight tool that is perfect for beginners and useful for experienced users too. We’ll keep it fun, easy to understand, and packed with examples and code, covering all the important aspects.



What is a Database and What are Tables?

A database is a special place on your computer where you store information in an organized way, like a digital notebook. Inside this notebook, you create tables, which are like charts or spreadsheets with rows and columns to hold your data. For example, if you’re keeping track of your favorite superheroes, a table might store their names, powers, and ages.

SQLite is a tool that helps you create and manage databases. It’s small, free, and works on almost any device, from your phone to your laptop. In this tutorial, we’ll learn how to:

  1. Create a database.
  2. Create tables to store data.
  3. Add some data to the tables.
  4. Look at the data to make sure it’s there.

Let’s dive in with a fun example: building a database for a pet store!



Why Use SQLite to Create Databases and Tables?

SQLite is awesome because it’s:

  • Simple: You don’t need to be a computer genius to use it.
  • Lightweight: It’s just one file, so it’s easy to move or share.
  • No Server Needed: Unlike other databases, SQLite works directly in your program or app.
  • Free: Anyone can use it without paying a penny.
  • Works Everywhere: From smartphones to video games, SQLite is used all over the place.

Think of SQLite as a tiny, magical librarian who helps you organize your data without needing a big library.



Getting Started with SQLite

To start, you need a way to use SQLite. The good news? SQLite is built into many programming languages like Python, which we’ll use in this tutorial because it’s beginner-friendly. If you don’t have Python installed, you can download it for free from python.org. SQLite comes with Python, so you don’t need to install anything extra.

You can also use a tool like DB Browser for SQLite (a free program with a friendly interface) if you prefer clicking buttons instead of coding. But for this tutorial, we’ll use Python to show you the code, which is a great way to learn.



Step 1: How to Create a Database in SQLite

When you create a database in SQLite, it’s stored as a single file on your computer (like petstore.db). This file holds all your tables and data. Let’s create a database for our pet store.

import sqlite3

# Connect to a database (creates a file called petstore.db if it doesn't exist)
conn = sqlite3.connect('petstore.db')

# Create a cursor to interact with the database
cursor = conn.cursor()

print("Database created successfully!")

# Close the connection when done
conn.close()


What’s Happening Here?

  • import sqlite3: This brings in the SQLite tools so we can use them in Python.
  • sqlite3.connect('petstore.db'): This creates a database file called petstore.db. If it already exists, it connects to it.
  • cursor: Think of this as your magical pen to write or read from the database.
  • conn.close(): This closes the database when you’re done, like closing your toy box.


Step 2: Create a Table in SQLite Using Python

Now that we have a database, let’s create a table to store information about pets in our pet store. A table needs columns to define what kind of data it will hold. For our pet store, we want to store:

  • PetID: A unique number for each pet.
  • Name: The pet’s name (like “Buddy”).
  • Type: The kind of animal (like “Dog” or “Cat”).
  • Age: How old the pet is.
  • Price: How much the pet costs.
import sqlite3

# Connect to the database
conn = sqlite3.connect('petstore.db')
cursor = conn.cursor()

# Create a table called Pets
cursor.execute('''
    CREATE TABLE IF NOT EXISTS Pets (
        PetID INTEGER PRIMARY KEY,
        Name TEXT,
        Type TEXT,
        Age REAL,
        Price REAL
    )
''')

# Save the changes
conn.commit()

print("Pets table created successfully!")

# Close the connection
conn.close()

What’s Happening Here?

  • CREATE TABLE IF NOT EXISTS Pets: This creates a table called Pets. The IF NOT EXISTS part means it won’t throw an error if the table already exists.
  • PetID INTEGER PRIMARY KEY: This makes PetID a unique number for each pet.
  • Name TEXT, Type TEXT: These store text.
  • Age REAL, Price REAL: These store decimal numbers.
  • conn.commit(): This saves your changes.


Step 3: Insert Data into SQLite Table

import sqlite3

# Connect to the database
conn = sqlite3.connect('petstore.db')
cursor = conn.cursor()

# Add pets to the table
cursor.execute("INSERT INTO Pets (Name, Type, Age, Price) VALUES ('Buddy', 'Dog', 2, 50.00)")
cursor.execute("INSERT INTO Pets (Name, Type, Age, Price) VALUES ('Whiskers', 'Cat', 1, 30.00)")
cursor.execute("INSERT INTO Pets (Name, Type, Age, Price) VALUES ('Goldie', 'Fish', 0.5, 5.00)")

# Save the changes
conn.commit()

print("Pets added successfully!")

# Close the connection
conn.close()

What’s Happening Here?

  • INSERT INTO Pets: This tells SQLite to add a new row to the table.
  • (Name, Type, Age, Price): Columns we’re filling.
  • VALUES ('Buddy', 'Dog', 2, 50.00): Sample data.

Now your table has three pets:

PetIDNameTypeAgePrice
1BuddyDog250.00
2WhiskersCat130.00
3GoldieFish0.55.00


Step 4: Query Data from SQLite Table

import sqlite3

# Connect to the database
conn = sqlite3.connect('petstore.db')
cursor = conn.cursor()

# Get all pets from the table
cursor.execute("SELECT * FROM Pets")
pets = cursor.fetchall()

# Print each pet
for pet in pets:
    print(pet)

# Close the connection
conn.close()

When you run this, you’ll see:

(1, 'Buddy', 'Dog', 2.0, 50.0)
(2, 'Whiskers', 'Cat', 1.0, 30.0)
(3, 'Goldie', 'Fish', 0.5, 5.0)


Step 5: Create Another SQLite Table – Bonus Example(For Fun!)

import sqlite3

# Connect to the database
conn = sqlite3.connect('petstore.db')
cursor = conn.cursor()

# Create a Customers table
cursor.execute('''
    CREATE TABLE IF NOT EXISTS Customers (
        CustomerID INTEGER PRIMARY KEY,
        Name TEXT,
        FavoritePetType TEXT
    )
''')

# Add some customers
cursor.execute("INSERT INTO Customers (Name, FavoritePetType) VALUES ('Alice', 'Dog')")
cursor.execute("INSERT INTO Customers (Name, FavoritePetType) VALUES ('Bob', 'Cat')")

# Save the changes
conn.commit()

print("Customers table created and data added successfully!")

# Close the connection
conn.close()

Sample Output Messages

Database created successfully!
Pets table created successfully!
Pets added successfully!
Customers table created and data added successfully!

Tips for Success with SQLite

  1. Start Simple: Begin with one table and a few rows.
  2. Practice SQL Commands: Learn CREATE, INSERT, SELECT.
  3. Use Tools: Try DB Browser for SQLite.
  4. Backup Your Database: Keep copies of your .db file.
  5. Experiment: Add more data, or create new tables.


Why Learn to Create Databases and Tables?

Learning to create databases and tables with SQLite is awesome because:

  • It’s Fun: Feels like solving a puzzle.
  • It’s Useful: Great for apps, games, or school projects.
  • It’s a Big Skill: Used everywhere.
  • It’s Easy: SQLite makes it simple.


Common Questions

1. Do I need coding skills to use SQLite?
Not always! Tools like DB Browser help, but coding gives you more power.

2. Can I use SQLite for big projects?
It’s great for small to medium projects. For huge systems, try MySQL or PostgreSQL.

3. Where is SQLite used?
In mobile apps, browsers, and video games.

4. Is my data safe in SQLite?
Yes, but always back up your .db file.



Quick Reference: SQLite Commands Used


Command Description
CREATE TABLE Creates a new table in the database
INSERT INTO Adds new data (rows) to a table
SELECT * FROM Retrieves all rows and columns from a table
conn.commit() Saves changes to the database
conn.close() Closes the connection to the database


Wrapping Up

Creating a database and tables with SQLite is like building your own magical toy box to store and organize data. It’s simple, fun, and a great skill for beginners and experts alike. In this tutorial, we created a petstore.db database, added a Pets table with Buddy, Whiskers, and Goldie, and even started a Customers table.

Try experimenting with your own database—maybe for your favorite books, movies, or PokΓ©mon collection. SQLite is easy to learn, free, and works everywhere, so it’s the perfect way to dive into the world of databases.

Happy database building, and have fun organizing your data!



Featured Post

SQL Server Transactions and Isolation Levels | Beginner to Expert Series - Part 13

Microsoft SQL Server Tutorial Series: Beginner to Expert Part 13: Transactions and Isolation Levels in SQL Server Welcome to Part 13 of ...

Popular Posts