mssql-python ile veri alın

mssql-python sürücüsü, sorgu sonuçlarını almak için çeşitli getirme yöntemleri, satır erişim desenleri ve imleç navigasyon özellikleri sunar.

Getirme yöntemleri

Bir SELECT sorgusu çalıştırdıktan sonra, sonuçları almak için fetch yöntemlerini kullanın.

fetchone()

Tek bir satır veya başka satır kalmamışsa None döndürür:

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()

Satır listesini döndürür. cursor.arraysize Varsayılan parti boyutunu kontrol eder (varsayılan: 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)

Boyutu doğrudan da belirtebilirsiniz:

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

fetchall()

Kalan tüm satırlar bir liste olarak döndürülür:

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()

İlk satırın ilk sütununu döndürür, bu da skaler sorgular için faydalıdır.

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}")

Satır erişim desenleri

Sınıf, Row çoklu erişim desenlerini destekler.

Indeks erişimi

Konuma göre (sıfır tabanlı) erişim sütunları:

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]

Öznitelik erişimi

Sütunlara isimle ulaşın:

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

Küçük harfli sütun adları

Öznitelik adlarını uygulama genelinde küçük harfe çevirin:

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

Yineleme

Satırlar, değerler üzerinde yinelemeyi destekler:

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

for value in row:
    print(value)

İmleç yinelemesi

Satırları işlemek için doğrudan imleç üzerinde yineleme yapın:

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

for row in cursor:
    print(row.Name)

Bu desen, fetchone() öğesini tekrar tekrar çağırmakla eşdeğerdir.

Sütun meta verileri

Sütun bilgisine şu adresten cursor.descriptionerişin:

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}")

Satır sayısı

Bu cursor.rowcount özellik şunu gösterir:

  • SELECT için: Getirme başlayana kadar execute() sonrasında -1 döndürür. Çekmeye başladığınızda, o ana kadar çekilen satırların kümülatif sayısını yansıtır.
  • INSERT/UPDATE/DELETE: Etkilenen satır sayısı.
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}")

İmleç navigasyonu

skip()

Satırları getirmeden atlayın:

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

scroll()

İmleç pozisyonunu ileriye taşıyın:

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

Sürücü yalnızca pozitif değerlere sahip mode='relative' öğesini destekler. Mutlak konumlandırma ve geriye kaydırma NotSupportedError yükseliyor çünkü sürücü sadece ileri imleç kullanıyor.

sıra numarası

Mevcut konumu takip edin:

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)

Birden fazla sonuç kümesi

Birden fazla sonuç kümesini işlemek için kullanılır nextset() :

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}")

Büyük sonuç kümeleri

Büyük sonuç kümeleri için, belleği yönetmek için satırlar halinde işlem yapın:

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")

Bağlam yöneticileri

Otomatik kaynak temizleme için bağlam yöneticileri kullanın:

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

En iyi uygulamalar

  • Her şeyi belleğe yüklemekten kaçınmak için büyük sonuçlarda fetchmany() kullanın.
  • Sunucu kaynaklarını serbest bırakmak için işiniz bittiğinde imleçleri kapatın.
  • Daha okunabilir kod için sütun adları (öznitelik erişimi) kullanın.
  • Kontrol rowcount Veri değiştirme ifadelerinden sonra.
  • Sütunlar null olabilir durumdaysa, None değerlerini açıkça işleyin.