Sådan forbinder du Python til SQL-databaser

At forbinde Python til SQL-databaser giver dig mulighed for at interagere med databaser direkte fra dine Python-scripts. Denne evne er afgørende for opgaver som datahentning, opdateringer og analyse. I denne artikel vil vi undersøge, hvordan du forbinder Python til SQL-databaser ved hjælp af populære biblioteker som SQLite, MySQL og PostgreSQL.

Opsætning af dit miljø

For at forbinde Python til SQL-databaser skal du installere de relevante databaseforbindelsesbiblioteker. Her er de fælles biblioteker for forskellige databaser:

  • SQLite: Ingen yderligere installation er nødvendig, da SQLite-understøttelse er indbygget i Python.
  • MySQL: Brug mysql-connector-python eller PyMySQL biblioteket.
  • PostgreSQL: Brug psycopg2 biblioteket.

Tilslutning til en SQLite-database

SQLite er en letvægtsdatabase, der er indbygget i Pythons standardbibliotek. Sådan opretter du forbindelse til en SQLite-database og udfører grundlæggende handlinger:

import sqlite3

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

# Create a cursor object
cursor = conn.cursor()

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

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

# Commit the transaction
conn.commit()

# Query the database
cursor.execute('SELECT * FROM users')
print(cursor.fetchall())  # Output: [(1, 'Alice', 30)]

# Close the connection
conn.close()

Tilslutning til en MySQL-database

For at oprette forbindelse til en MySQL-database skal du installere mysql-connector-python-biblioteket. Du kan installere det ved hjælp af pip:

pip install mysql-connector-python

Her er et eksempel på at oprette forbindelse til en MySQL-database og udføre grundlæggende handlinger:

import mysql.connector

# Connect to a MySQL database
conn = mysql.connector.connect(
    host='localhost',
    user='yourusername',
    password='yourpassword',
    database='testdb'
)

# Create a cursor object
cursor = conn.cursor()

# Create a table
cursor.execute('''
CREATE TABLE IF NOT EXISTS employees (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    position VARCHAR(255)
)
''')

# Insert data into the table
cursor.execute('''
INSERT INTO employees (name, position)
VALUES ('Bob', 'Engineer')
''')

# Commit the transaction
conn.commit()

# Query the database
cursor.execute('SELECT * FROM employees')
print(cursor.fetchall())  # Output: [(1, 'Bob', 'Engineer')]

# Close the connection
conn.close()

Tilslutning til en PostgreSQL-database

For at oprette forbindelse til en PostgreSQL-database skal du bruge psycopg2-biblioteket. Installer det ved hjælp af pip:

pip install psycopg2

Her er et eksempel på at oprette forbindelse til en PostgreSQL-database og udføre grundlæggende handlinger:

import psycopg2

# Connect to a PostgreSQL database
conn = psycopg2.connect(
    dbname='testdb',
    user='yourusername',
    password='yourpassword',
    host='localhost'
)

# Create a cursor object
cursor = conn.cursor()

# Create a table
cursor.execute('''
CREATE TABLE IF NOT EXISTS products (
    id SERIAL PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    price DECIMAL
)
''')

# Insert data into the table
cursor.execute('''
INSERT INTO products (name, price)
VALUES ('Laptop', 999.99)
''')

# Commit the transaction
conn.commit()

# Query the database
cursor.execute('SELECT * FROM products')
print(cursor.fetchall())  # Output: [(1, 'Laptop', 999.99)]

# Close the connection
conn.close()

Konklusion

At forbinde Python til SQL-databaser er en grundlæggende færdighed for enhver datadrevet applikation. Ved at bruge biblioteker som sqlite3, mysql-connector-python og psycopg2, kan du nemt interagere med forskellige databaser. At forstå, hvordan du udfører grundlæggende handlinger såsom oprettelse af tabeller, indsættelse af data og forespørgsler i databaser, vil gøre dig i stand til at administrere og manipulere dine data effektivt.