How do I use Python with databases

Python provides various ways to interact with databases, including libraries and frameworks that facilitate database connections, querying, and handling data efficiently. One of the most popular libraries for database interaction in Python is SQLite, but Python can also connect to other databases like MySQL, PostgreSQL, and Oracle.

Python, databases, SQLite, MySQL, PostgreSQL, database interaction, querying, data handling
Learn how to use Python to connect with various databases and execute SQL queries. Discover libraries like SQLite and how to efficiently manage data with Python.
import sqlite3

# Connect to a database (or create it if it doesn't exist)
connection = sqlite3.connect('example.db')

# Create a cursor object to execute SQL commands
cursor = connection.cursor()

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

# Insert a new user into the table
cursor.execute('''INSERT INTO users (name, age) VALUES (?, ?)''', ('Alice', 30))

# Commit the transaction
connection.commit()

# Query the table
cursor.execute('''SELECT * FROM users''')

# Fetch and print all results
results = cursor.fetchall()
for row in results:
    print(row)

# Close the connection
connection.close()
        

Python databases SQLite MySQL PostgreSQL database interaction querying data handling