Lavoro con dati binari

Il driver mssql-python supporta binary, varbinary, e image i tipi di dati per Microsoft SQL.

Microsoft SQL memorizza i dati binari in questi tipi di colonne:

TIPO Descrizione Dimensioni massime
binary(n) Dati binari a lunghezza fissa. 8.000 byte
varbinary(n) Dati binari a lunghezza variabile. 8.000 byte
varbinary(max) Dati binari di grandi dimensioni. 2GB
image Dati binari di grandi dimensioni precedenti (deprecati). 2GB

Il driver mssql-python restituisce dati binari come oggetti Pythonbytes.

Quando memorizzare il binario nel database rispetto al file system:

  • Memorizza nel database quando i file sono piccoli (meno di 1 MB), la coerenza transazionale con altri dati è importante, oppure devi fare il backup insieme di dati e file.
  • Memorizza nel file system (o Archiviazione BLOB di Azure) quando i file sono grandi (oltre 1 MB), quando serve la consegna CDN, oppure devi servire i file direttamente ai client senza fare i dati di andata e ritorno al database.
  • Come soluzione intermedia, la funzionalità FILESTREAM di Microsoft SQL memorizza i dati nel file system con coerenza transazionale.

Inserire dati binari

Passa oggetti Python bytes come parametri; il driver li mappa a colonne varbinary.

Inserire byte direttamente

Crea un oggetto Python bytes e passalo come parametro di query:

import mssql_python

conn = mssql_python.connect(connection_string)
cursor = conn.cursor()

# Create a table to hold binary documents
cursor.execute("""
    CREATE TABLE #Documents (
        ID INT IDENTITY PRIMARY KEY,
        Name NVARCHAR(255),
        Content VARBINARY(MAX),
        Size INT NULL,
        ContentHash VARBINARY(32) NULL
    )
""")

# Binary data as bytes
binary_data = b'\x00\x01\x02\x03\x04\x05'

cursor.execute(
    "INSERT INTO #Documents (Name, Content) VALUES (%(name)s, %(content)s)",
    {"name": "sample.bin", "content": binary_data}
)
conn.commit()

Inserire dal file

Leggi un file in modalità binaria e inserisci il suo contenuto:

def insert_file(cursor, file_path: str, name: str):
    """Insert a file as binary data."""
    with open(file_path, "rb") as f:
        content = f.read()
    
    cursor.execute(
        "INSERT INTO #Documents (Name, Content, Size) VALUES (%(name)s, %(content)s, %(size)s)",
        {"name": name, "content": content, "size": len(content)}
    )

insert_file(cursor, "image.png", "profile_picture.png")
conn.commit()

Inserisci file immagine

Memorizza i file immagine con i metadati rilevando i tipi MIME dalle estensioni dei file:

# Create a table to hold images
cursor.execute("""
    CREATE TABLE #Images (
        ID INT IDENTITY PRIMARY KEY,
        FileName NVARCHAR(255),
        FileSize INT NULL,
        ContentType NVARCHAR(100) NULL,
        Width INT NULL,
        Height INT NULL,
        ImageData VARBINARY(MAX),
        Description NVARCHAR(MAX) NULL
    )
""")

def insert_image(cursor, image_path: str, description: str):
    """Insert an image into the database."""
    import os
    
    with open(image_path, "rb") as f:
        image_data = f.read()
    
    cursor.execute("""
        INSERT INTO #Images (FileName, FileSize, ContentType, ImageData, Description)
        VALUES (%(filename)s, %(filesize)s, %(content_type)s, %(data)s, %(desc)s)
    """, {
        "filename": os.path.basename(image_path),
        "filesize": len(image_data),
        "content_type": get_content_type(image_path),
        "data": image_data,
        "desc": description
    })

def get_content_type(path: str) -> str:
    """Determine MIME type from file extension."""
    ext = path.lower().split(".")[-1]
    types = {
        "png": "image/png",
        "jpg": "image/jpeg",
        "jpeg": "image/jpeg",
        "gif": "image/gif",
        "pdf": "application/pdf",
    }
    return types.get(ext, "application/octet-stream")

Recuperare i dati binari

Il driver restituisce valori varbinari e binari delle colonne come oggetti Pythonbytes.

Recupera colonna binaria

Interroga le colonne binarie e ispeziona l'oggetto restituito bytes :

cursor.execute(
    "SELECT LargePhotoFileName, LargePhoto FROM Production.ProductPhoto WHERE ProductPhotoID = %(id)s",
    {"id": 70}
)
row = cursor.fetchone()

# LargePhoto is bytes
print(type(row.LargePhoto))  # <class 'bytes'>
print(len(row.LargePhoto))   # Number of bytes

Salvare su file

Recupera i dati binari e scrivili su disco:

def save_photo(cursor, photo_id: int, output_path: str):
    """Retrieve binary data and save to file."""
    cursor.execute(
        "SELECT LargePhoto FROM Production.ProductPhoto WHERE ProductPhotoID = %(id)s",
        {"id": photo_id}
    )
    row = cursor.fetchone()
    
    if row and row.LargePhoto:
        with open(output_path, "wb") as f:
            f.write(row.LargePhoto)
        print(f"Saved {len(row.LargePhoto)} bytes to {output_path}")
    else:
        print("Photo not found or empty")

save_photo(cursor, 70, "output.gif")

Esporta righe binarie nei file

Esporta più righe binarie in file locali:

import os

def export_photos(cursor, output_dir: str):
    """Export product photos to a directory."""
    os.makedirs(output_dir, exist_ok=True)
    
    cursor.execute("""
        SELECT ProductPhotoID, LargePhotoFileName, LargePhoto
        FROM Production.ProductPhoto
        WHERE ProductPhotoID > 1
    """)
    
    count = 0
    for row in cursor:
        output_path = os.path.join(output_dir, f"{row.ProductPhotoID}_{row.LargePhotoFileName}")
        with open(output_path, "wb") as f:
            f.write(row.LargePhoto)
        count += 1
    
    print(f"Exported {count} photos to {output_dir}")

export_photos(cursor, "./photos")

Inserire valori binari NULL

Pass None per inserire un SQL NULL in una colonna binaria. Poiché #Documents è una tabella temporanea, dichiarare i tipi dei parametri utilizzando prima setinputsizes(), in modo che il driver associ Content come varbinary:

cursor.setinputsizes([(mssql_python.SQL_WVARCHAR, 255, 0), (mssql_python.SQL_VARBINARY, 0, 0)])
cursor.execute(
    "INSERT INTO #Documents (Name, Content) VALUES (%(name)s, %(content)s)",
    {"name": "empty", "content": None}
)

Note

Il driver normalmente deduce i tipi di parametri tramite SQLDescribeParam, ma non può risolvere i metadati di tipo per una tabellatemporanea o una variabile della tabella. L'inserimento di None in una colonna binary o varbinary di un oggetto temporaneo senza setinputsizes() genera ProgrammingError: Implicit conversion from data type varchar to varbinary(max) is not allowed. Passa una voce per parametro, in ordine, e usa una costante di tipo SQL come mssql_python.SQL_VARBINARY per la colonna binaria. Per una tabella normale (permanente), il driver risolve automaticamente il tipo ed è possibile passare direttamente None.

Dati binari di grandi dimensioni

Per file di oltre pochi megabyte, inserisci il contenuto completo in una singola scrittura varbinary(max ) invece di leggere il file in piccoli blocchi.

Trasmetti file di grandi dimensioni

Per file grandi, elaborare a blocchi:

def insert_large_file(conn, table: str, file_path: str, chunk_size: int = 8192):
    """Insert large file in chunks using updatetext-style approach."""
    # Validate table name to prevent SQL injection
    import re
    if not re.match(r'^#{0,2}[A-Za-z_][A-Za-z0-9_.]*$', table):
        raise ValueError(f"Invalid table name: {table}")

    cursor = conn.cursor()
    
    # Get file size
    import os
    file_size = os.path.getsize(file_path)
    
    # Insert initial row with empty binary
    cursor.execute(f"""
        INSERT INTO {table} (Name, Content, Size)
        VALUES (%(name)s, 0x, %(size)s);
        SELECT SCOPE_IDENTITY();
    """, {"name": os.path.basename(file_path), "size": file_size})
    
    row_id = cursor.fetchval()
    
    # For modern Microsoft SQL, better to use varbinary(max) and single insert
    # This example shows streaming approach
    with open(file_path, "rb") as f:
        content = f.read()
    
    cursor.execute(f"""
        UPDATE {table} SET Content = %(content)s WHERE ID = %(id)s
    """, {"content": content, "id": row_id})
    
    conn.commit()
    return row_id

Usa copia in blocco per i dati binari

Usa il bulkcopy() metodo per inserire in modo efficiente più file binari in un'unica operazione.

Importante

bulkcopy() carica i dati tramite una connessione separata al server, quindi la tabella di destinazione deve già esistere ed essere validata e visibile ad altre sessioni. Se crei la tabella nello stesso script con l'autocommit disattivato, chiama conn.commit() prima di bulkcopy(). Le tabelle temporanee locali (#name) non sono supportate perché sono private della sessione che le ha create. Una destinazione non confermata o irraggiungibile fa sì che bulkcopy() non riesca con un timeout di Failed to retrieve destination metadata.

Di default, bulkcopy() mappa ogni valore di una riga a una colonna di tabella per posizione ordinale, quindi ogni colonna deve avere un valore in ordine. Quando la tabella ha una colonna Identity o si popolano solo alcune colonne, passa column_mappings per specificare esplicitamente le colonne di destinazione. Altrimenti i valori si spostano sulle colonne sbagliate e bulkcopy() falliscono.

def bulk_insert_files(conn, table: str, file_paths: list[str]):
    """Bulk insert multiple binary files."""
    import os

    data = []
    for path in file_paths:
        with open(path, "rb") as f:
            content = f.read()
        data.append((os.path.basename(path), content, len(content)))

    cursor = conn.cursor()
    result = cursor.bulkcopy(table, data, column_mappings=["Name", "Content", "Size"])
    conn.commit()
    return result["rows_copied"]

Operazioni dati binarie

Usa la funzione di HASHBYTES Microsoft SQL per confrontare contenuti binari senza dover recuperare valori completi.

Confronta i dati binari

Trova righe binarie che condividono contenuti identici calcolando e confrontando gli hash dei contenuti in Microsoft SQL Server:

# Find rows with identical binary content by hash
cursor.execute("""
    SELECT LargePhotoFileName, HASHBYTES('SHA2_256', LargePhoto) AS PhotoHash
    FROM Production.ProductPhoto
    WHERE ProductPhotoID > 1
""")

hashes = {}
for row in cursor:
    hash_value = row.PhotoHash  # bytes
    if hash_value in hashes:
        print(f"Duplicate: {row.LargePhotoFileName} matches {hashes[hash_value]}")
    else:
        hashes[hash_value] = row.LargePhotoFileName

Calcolare l'hash in Python

Calcola gli hash SHA-256 in Python e memorizzali insieme ai dati binari:

import hashlib

def insert_with_hash(cursor, name: str, content: bytes):
    """Insert binary data with computed hash."""
    content_hash = hashlib.sha256(content).digest()
    
    cursor.execute("""
        INSERT INTO #Documents (Name, Content, ContentHash)
        VALUES (%(name)s, %(content)s, %(hash)s)
    """, {"name": name, "content": content, "hash": content_hash})

Codifica e decodifica dati binari

Converti i dati binari da e verso stringhe codificate in base64:

import base64

# Store base64-encoded string
def insert_base64(cursor, name: str, base64_data: str):
    """Insert base64-encoded data as binary."""
    binary_data = base64.b64decode(base64_data)
    cursor.execute(
        "INSERT INTO #Documents (Name, Content) VALUES (%(name)s, %(content)s)",
        {"name": name, "content": binary_data}
    )

# Retrieve as base64
def get_as_base64(cursor, doc_id: int) -> str:
    """Retrieve binary data as base64 string."""
    cursor.execute("SELECT Content FROM #Documents WHERE ID = %(id)s", {"id": doc_id})
    row = cursor.fetchone()
    return base64.b64encode(row.Content).decode("utf-8")

Lavoro con formati binari specifici

Questi esempi mostrano come validare e inserire formati di file comuni prima di memorizzarli.

Documenti PDF

Verifica le firme dei file PDF prima di inserirle:

def insert_pdf(cursor, pdf_path: str, title: str):
    """Insert a PDF document."""
    with open(pdf_path, "rb") as f:
        pdf_data = f.read()
    
    # Verify it's a PDF (magic bytes)
    if not pdf_data.startswith(b'%PDF'):
        raise ValueError("Not a valid PDF file")
    
    cursor.execute(
        "INSERT INTO #Documents (Name, Content) VALUES (%(title)s, %(data)s)",
        {"title": title, "data": pdf_data}
    )

Immagini con PIL/Pillow

Ridimensiona le immagini usando Pillow (PIL) prima di conservarle per risparmiare spazio:

from PIL import Image
import io
import os

def insert_resized_image(cursor, image_path: str, max_size: tuple = (800, 600)):
    """Insert a resized image."""
    # Open and resize
    img = Image.open(image_path)
    img.thumbnail(max_size, Image.LANCZOS)
    
    # Convert to bytes
    buffer = io.BytesIO()
    img.save(buffer, format=img.format or "PNG")
    image_bytes = buffer.getvalue()
    
    cursor.execute("""
        INSERT INTO #Images (FileName, Width, Height, ImageData)
        VALUES (%(name)s, %(width)s, %(height)s, %(data)s)
    """, {
        "name": os.path.basename(image_path),
        "width": img.width,
        "height": img.height,
        "data": image_bytes
    })

def get_image_as_pil(cursor, image_id: int) -> Image.Image:
    """Retrieve image as PIL Image object."""
    cursor.execute("SELECT ImageData FROM #Images WHERE ID = %(id)s", {"id": image_id})
    row = cursor.fetchone()
    return Image.open(io.BytesIO(row.ImageData))

Dati compressi

Ridurre lo spazio comprimendo i dati binari con gzip prima dell'inserimento:

import gzip

def insert_compressed(cursor, name: str, data: bytes):
    """Insert data with gzip compression."""
    compressed = gzip.compress(data)
    
    cursor.execute(
        "INSERT INTO #Documents (Name, Content, Size) VALUES (%(name)s, %(content)s, %(size)s)",
        {"name": name, "content": compressed, "size": len(data)}
    )

def get_decompressed(cursor, data_id: int) -> bytes:
    """Retrieve and decompress data."""
    cursor.execute(
        "SELECT Content FROM #Documents WHERE ID = %(id)s",
        {"id": data_id}
    )
    row = cursor.fetchone()
    return gzip.decompress(row.Content)

Procedure consigliate

Applica queste linee guida per scegliere il tipo di colonna giusto e la strategia di archiviazione per i dati binari.

Usa tipi di colonne appropriati

Scegli il tipo di colonna in base alle caratteristiche dei tuoi dati:

Per diversi casi d'uso binari, seleziona il tipo di dato Microsoft SQL appropriato:

-- For small fixed-size binary (for example, hashes, UUIDs)
binary(32)      -- SHA-256 hash

-- For variable-size binary up to 8KB (for example, thumbnails, small icons)
varbinary(8000)

-- For large binary data (for example, documents, images)
varbinary(max)  -- Up to 2GB

Considera FILESTREAM per file di grandi dimensioni

Per file di grandi dimensioni (oltre 1 MB), considerate la funzione Microsoft SQL FILESTREAM, che memorizza i dati nel file system. FILESTREAM richiede la configurazione lato server prima dell'uso:

# FILESTREAM-enabled databases store large binaries more efficiently
# Access is still through normal queries but storage is file-based
large_binary_data = b"\x25\x50\x44\x46" + b"\x00" * 100  # sample data

cursor.execute("""
    CREATE TABLE ##FileStreamDemo (Name NVARCHAR(100), Document VARBINARY(MAX))
""")
cursor.execute("""
    INSERT INTO ##FileStreamDemo (Name, Document)
    VALUES (%(name)s, %(content)s)
""", {"name": "large_doc.pdf", "content": large_binary_data})

cursor.execute("SELECT Name, DATALENGTH(Document) AS DocSize FROM ##FileStreamDemo")
row = cursor.fetchone()
print(f"{row.Name}: {row.DocSize} bytes")

Convalidare i dati binari

Valida i tipi di file controllando i magic byte (firme dei file) prima di memorizzare dati binari:

def insert_safe_image(cursor, name: str, data: bytes):
    """Insert image with validation."""
    # Check file signatures (magic bytes)
    signatures = {
        b'\x89PNG': 'image/png',
        b'\xff\xd8\xff': 'image/jpeg',
        b'GIF87a': 'image/gif',
        b'GIF89a': 'image/gif',
    }
    
    content_type = None
    for sig, mime in signatures.items():
        if data.startswith(sig):
            content_type = mime
            break
    
    if content_type is None:
        raise ValueError("Unknown or unsupported image format")
    
    cursor.execute("""
        INSERT INTO #Images (FileName, ContentType, ImageData)
        VALUES (%(name)s, %(type)s, %(data)s)
    """, {"name": name, "type": content_type, "data": data})