w1coding.comAll tutorials

Python SQLite

Python lessons
  1. Environment Setup
  2. Introduction
  3. Control
  4. Control
  5. Loops
  6. Functions
  7. Lists
  8. Dictionary
  9. Classes
  10. Exception
  11. File
  12. Libray
  13. Date
  14. Regula
  15. JSON
  16. Web
  17. Zweb
  18. Apis
  19. Unity
  20. Llampda
  21. Iterators
  22. Generators
  23. Files
  24. Context
  25. Ilogging
  26. Multithreading
  27. Networking
  28. SQLite

SQLite is a lightweight, disk-based database that doesn't require a separate server process. Python has built-in support for SQLite through the sqlite3 module.

Creating a Database

You can create a new SQLite database and perform CRUD (Create, Read, Update, Delete) operations:

      
        import sqlite3

        # Connect to the database (or create it)
        conn = sqlite3.connect('example.db')
        cursor = conn.cursor()

        # Create a table
        cursor.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')

        # Insert data
        cursor.execute("INSERT INTO users (name, age) VALUES ('Alice', 30)")
        conn.commit()

        # Query data
        cursor.execute("SELECT * FROM users")
        rows = cursor.fetchall()
        for row in rows:
            print(row)

        conn.close()
      
    

Activity

Try It Yourself!

Create a database that stores books, including the title, author, and publication year. Insert a few records and retrieve them.

Quick Quiz

Quick Quiz

  1. What is SQLite?
  2. Which Python module is used to interact with SQLite databases?

Answers: SQLite is a lightweight, disk-based database