Daten mit mssql-python abrufen

Der mssql-python-Treiber bietet mehrere Abrufmethoden, Zeilenzugriffsmuster und Cursornavigationsfunktionen zum Abruf von Abfrageergebnissen.

Abrufmethoden

Nach Ausführung einer SELECT-Abfrage verwenden Sie Fetch-Methoden, um Ergebnisse abzurufen.

fetchone()

Gibt eine einzelne Zeile zurück oder None wenn keine weiteren Zeilen verfügbar sind:

cursor.execute("SELECT ProductID, Name, ListPrice FROM Production.Product")

row = cursor.fetchone()
while row:
    print(f"{row.ProductID}: {row.Name} - ${row.ListPrice}")
    row = cursor.fetchone()

fetchmany()

Gibt eine Liste von Zeilen zurück. cursor.arraysize Steuert die Standard-Chargengröße (Standard: 1):

cursor.execute("SELECT * FROM Production.Product")
cursor.arraysize = 100  # Fetch 100 rows at a time

while True:
    rows = cursor.fetchmany()
    if not rows:
        break
    for row in rows:
        print(row.Name)

Du kannst auch die Größe direkt angeben:

rows = cursor.fetchmany(50)  # Fetch up to 50 rows

fetchall()

Gibt alle verbleibenden Zeilen als Liste zurück:

cursor.execute("SELECT * FROM Production.Product WHERE Color = 'Black'")
rows = cursor.fetchall()

print(f"Found {len(rows)} products")
for row in rows:
    print(row.Name)

fetchval()

Gibt die erste Spalte der ersten Zeile zurück, was für skalare Abfragen nützlich ist.

count = cursor.execute("SELECT COUNT(*) FROM Production.Product").fetchval()
print(f"Total products: {count}")

max_price = cursor.execute("SELECT MAX(ListPrice) FROM Production.Product").fetchval()
print(f"Highest price: ${max_price}")

Zeilenzugriffsmuster

Die Klasse Row unterstützt mehrere Zugriffsmuster.

Indexzugriff

Auf Spalten nach Position (nullbasiert) zugreifen:

cursor.execute("SELECT ProductID, Name, ListPrice FROM Production.Product WHERE ProductID < 5")
row = cursor.fetchone()

product_id = row[0]
name = row[1]
price = row[2]

Attributzugriff

Auf Spalten nach Name zugreifen:

cursor.execute("SELECT ProductID, Name, ListPrice FROM Production.Product WHERE ProductID < 5")
row = cursor.fetchone()

product_id = row.ProductID
name = row.Name
price = row.ListPrice

Spaltennamen in Kleinbuchstaben

Aktivieren Sie globale Kleinbuchstaben-Attributnamen:

import mssql_python

settings = mssql_python.get_settings()
settings.lowercase = True

cursor.execute("SELECT ProductID, Name FROM Production.Product WHERE ProductID < 5")
row = cursor.fetchone()
print(row.productid, row.name)  # Lowercase access
settings.lowercase = False  # Restore default

Iteration

Zeilen unterstützen Iteration über Werte:

cursor.execute("SELECT ProductID, Name, ListPrice FROM Production.Product WHERE ProductID < 5")
row = cursor.fetchone()

for value in row:
    print(value)

Cursor-Durchlauf

Iterieren Sie direkt über den Cursor, um Zeilen zu verarbeiten:

cursor.execute("SELECT * FROM Production.Product")

for row in cursor:
    print(row.Name)

Dieses Muster entspricht einem wiederholten Anruf fetchone() .

Spaltenmetadaten

Zugreifen Sie auf Spalteninformationen über cursor.description:

cursor.execute("SELECT ProductID, Name, ListPrice FROM Production.Product WHERE ProductID < 5")

for col in cursor.description:
    name, type_code, display_size, internal_size, precision, scale, null_ok = col
    print(f"Column: {name}, Type: {type_code}, Nullable: {null_ok}")

Zeilenanzahl

Das Attribut cursor.rowcount zeigt an:

  • Für SELECT: Wird nach execute() -1 zurückgegeben, bis der Abruf beginnt. Sobald du mit dem Abrufen beginnst, wird die Gesamtzahl der bisher abgerufenen Zeilen angezeigt.
  • Für INSERT/UPDATE/DELETE: Anzahl der betroffenen Zeilen.
cursor.execute("SELECT * FROM Production.Product")
print(f"Rows returned: {cursor.rowcount}")

cursor.execute("CREATE TABLE #PriceUpd (Name NVARCHAR(50), Price DECIMAL(10,2), CategoryID INT)")
cursor.execute("INSERT INTO #PriceUpd VALUES ('A',10,1),('B',20,1),('C',30,2)")
cursor.execute("UPDATE #PriceUpd SET Price = Price * 1.1 WHERE CategoryID = 1")
print(f"Rows updated: {cursor.rowcount}")

Cursornavigation

skip()

Zeilen überspringen, ohne sie abzurufen:

cursor.execute("SELECT * FROM Production.Product ORDER BY ProductID")
cursor.skip(10)  # Skip first 10 rows
row = cursor.fetchone()  # Returns 11th row

scroll()

Verschiebe die Cursorposition nach vorne:

cursor.execute("SELECT * FROM Production.Product ORDER BY ProductID")

# Move forward 5 rows from current position
cursor.scroll(5, mode='relative')

row = cursor.fetchone()

Note

Der Treiber unterstützt nur mode='relative' mit positiven Werten. Absolute Positionierung und Rückwärtsscrollen lösen NotSupportedError aus, weil der Treiber nur vorwärtsgerichtete Cursor verwendet.

Zeilennummer

Verfolgen Sie die aktuelle Position:

cursor.execute("SELECT * FROM Production.Product")

print(f"Initial position: {cursor.rownumber}")  # -1 (before first fetch)

row = cursor.fetchone()
print(f"After fetchone: {cursor.rownumber}")    # 0 (first row fetched)

Mehrere Ergebnismengen

Verwenden Sie nextset(), um mehrere Ergebnismengen zu verarbeiten:

cursor.execute("""
    SELECT * FROM Production.Product WHERE Color = 'Black';
    SELECT * FROM Production.ProductCategory;
    SELECT COUNT(*) FROM Production.Product;
""")

# First result set
products = cursor.fetchall()
print(f"Products: {len(products)}")

# Move to second result set
if cursor.nextset():
    categories = cursor.fetchall()
    print(f"Categories: {len(categories)}")

# Move to third result set
if cursor.nextset():
    count = cursor.fetchval()
    print(f"Total count: {count}")

Große Ergebnismengen

Für große Ergebnismengen werden Zeilen in Batches verarbeitet, um den Speicher zu verwalten:

def process_batch(rows):
    # Example: print each row. Replace with your own logic.
    for row in rows:
        print(row)

cursor.execute("SELECT * FROM LargeTable")
cursor.arraysize = 1000

while True:
    rows = cursor.fetchmany()
    if not rows:
        break

    process_batch(rows)
    print(f"Processed {cursor.rownumber} rows so far")

Kontextmanager

Verwenden Sie Kontextmanager für die automatische Ressourcenbereinigung:

with mssql_python.connect(connection_string) as conn:
    with conn.cursor() as cursor:
        cursor.execute("SELECT * FROM Production.Product")
        for row in cursor:
            print(row.Name)
# Cursor and connection closed automatically

Bewährte Methoden

  • Verwenden fetchmany() Sie für große Ergebnisse, um zu vermeiden, dass alles in den Speicher geladen wird.
  • Schließen Sie die Cursor, wenn Sie fertig sind, um Serverressourcen freizugeben.
  • Verwenden Sie Spaltennamen (Attributzugriff) für lesbareren Code.
  • Prüfen Sie rowcount nach Anweisungen zur Datenänderung.
  • Werte werden explizit behandeltNone, wenn Spalten nullfähig sind.