Python'da MySQL Kullanımı (Detaylı Anlatım)
Python'da MySQL veritabanı ile çalışmak için genellikle mysql-connector-python veya PyMySQL kütüphaneleri kullanılır. Bu rehberde her iki yöntemi de detaylı şekilde anlatacağım.
1. Gerekli Kütüphanelerin Kurulumu
Önce gerekli kütüphaneleri yükleyelim:
pip install mysql-connector-python pymysql2. MySQL Connector/Python Kullanımı
Bağlantı Oluşturma
import mysql.connector
from mysql.connector import Error
try:
connection = mysql.connector.connect(
host='localhost',
database='veritabani_adi',
user='kullanici_adi',
password='sifre'
)
if connection.is_connected():
db_info = connection.get_server_info()
print(f"MySQL sunucusuna bağlanıldı - Versiyon: {db_info}")
cursor = connection.cursor()
cursor.execute("select database();")
record = cursor.fetchone()
print(f"Bağlı olduğunuz veritabanı: {record[0]}")
except Error as e:
print("MySQL'e bağlanırken hata oluştu:", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL bağlantısı kapatıldı")Tablo Oluşturma
try:
connection = mysql.connector.connect(
host='localhost',
database='veritabani_adi',
user='kullanici_adi',
password='sifre'
)
cursor = connection.cursor()
create_table_query = """
CREATE TABLE IF NOT EXISTS musteriler (
id INT AUTO_INCREMENT PRIMARY KEY,
ad VARCHAR(255),
soyad VARCHAR(255),
email VARCHAR(255),
kayit_tarihi DATETIME DEFAULT CURRENT_TIMESTAMP
)
"""
cursor.execute(create_table_query)
print("Tablo başarıyla oluşturuldu")
except Error as e:
print("Hata oluştu:", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()Veri Ekleme (INSERT)
try:
connection = mysql.connector.connect(
host='localhost',
database='veritabani_adi',
user='kullanici_adi',
password='sifre'
)
cursor = connection.cursor()
insert_query = """
INSERT INTO musteriler (ad, soyad, email)
VALUES (%s, %s, %s)
"""
values = ("Ahmet", "Yılmaz", "ahmet@example.com")
cursor.execute(insert_query, values)
connection.commit() # Değişiklikleri kaydetmek için önemli!
print(cursor.rowcount, "kayıt eklendi")
except Error as e:
print("Hata oluştu:", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()Çoklu Veri Ekleme
try:
connection = mysql.connector.connect(
host='localhost',
database='veritabani_adi',
user='kullanici_adi',
password='sifre'
)
cursor = connection.cursor()
insert_query = """
INSERT INTO musteriler (ad, soyad, email)
VALUES (%s, %s, %s)
"""
values = [
("Mehmet", "Demir", "mehmet@example.com"),
("Ayşe", "Kaya", "ayse@example.com"),
("Fatma", "Şahin", "fatma@example.com")
]
cursor.executemany(insert_query, values)
connection.commit()
print(cursor.rowcount, "kayıt eklendi")
except Error as e:
print("Hata oluştu:", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()Veri Sorgulama (SELECT)
try:
connection = mysql.connector.connect(
host='localhost',
database='veritabani_adi',
user='kullanici_adi',
password='sifre'
)
cursor = connection.cursor(dictionary=True) # Sözlük formatında sonuç almak için
select_query = "SELECT * FROM musteriler"
cursor.execute(select_query)
records = cursor.fetchall()
print("Toplam kayıt sayısı:", cursor.rowcount)
for row in records:
print("ID:", row["id"])
print("Ad:", row["ad"])
print("Soyad:", row["soyad"])
print("Email:", row["email"])
print("Kayıt Tarihi:", row["kayit_tarihi"])
print("-" * 20)
except Error as e:
print("Hata oluştu:", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()Veri Güncelleme (UPDATE)
try:
connection = mysql.connector.connect(
host='localhost',
database='veritabani_adi',
user='kullanici_adi',
password='sifre'
)
cursor = connection.cursor()
update_query = """
UPDATE musteriler
SET email = %s
WHERE id = %s
"""
values = ("ahmet.yilmaz@example.com", 1)
cursor.execute(update_query, values)
connection.commit()
print(cursor.rowcount, "kayıt güncellendi")
except Error as e:
print("Hata oluştu:", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()Veri Silme (DELETE)
try:
connection = mysql.connector.connect(
host='localhost',
database='veritabani_adi',
user='kullanici_adi',
password='sifre'
)
cursor = connection.cursor()
delete_query = "DELETE FROM musteriler WHERE id = %s"
values = (2,)
cursor.execute(delete_query, values)
connection.commit()
print(cursor.rowcount, "kayıt silindi")
except Error as e:
print("Hata oluştu:", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()3. PyMySQL Kullanımı
PyMySQL, MySQL Connector'a alternatif bir kütüphanedir. Kullanımı benzerdir:
Bağlantı ve Temel İşlemler
import pymysql
from pymysql import Error
try:
connection = pymysql.connect(
host='localhost',
user='kullanici_adi',
password='sifre',
database='veritabani_adi',
cursorclass=pymysql.cursors.DictCursor # Sözlük formatında sonuç
)
with connection.cursor() as cursor:
# Veri ekleme
sql = "INSERT INTO musteriler (ad, soyad, email) VALUES (%s, %s, %s)"
cursor.execute(sql, ("Ali", "Veli", "ali@example.com"))
connection.commit()
# Veri sorgulama
cursor.execute("SELECT * FROM musteriler")
results = cursor.fetchall()
for row in results:
print(row)
except Error as e:
print("Hata oluştu:", e)
finally:
if connection:
connection.close()Transaction Yönetimi
try:
connection = pymysql.connect(
host='localhost',
user='kullanici_adi',
password='sifre',
database='veritabani_adi'
)
try:
with connection.cursor() as cursor:
# İşlem 1
sql1 = "UPDATE hesaplar SET bakiye = bakiye - 100 WHERE id = 1"
cursor.execute(sql1)
# İşlem 2
sql2 = "UPDATE hesaplar SET bakiye = bakiye + 100 WHERE id = 2"
cursor.execute(sql2)
# Her iki işlem de başarılı olursa commit
connection.commit()
print("Transfer başarılı")
except Error as e:
# Hata durumunda rollback
connection.rollback()
print("Transfer başarısız, işlemler geri alındı:", e)
except Error as e:
print("Bağlantı hatası:", e)
finally:
if connection:
connection.close()4. ORM Kullanımı: SQLAlchemy ile MySQL
Daha gelişmiş projelerde ORM (Object-Relational Mapping) kütüphaneleri kullanılabilir:
from sqlalchemy import create_engine, Column, Integer, String, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from datetime import datetime
# Veritabanı bağlantısı
SQLALCHEMY_DATABASE_URL = "mysql+pymysql://kullanici_adi:sifre@localhost/veritabani_adi"
engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
# Model tanımı
class Musteri(Base):
__tablename__ = "musteriler"
id = Column(Integer, primary_key=True, index=True)
ad = Column(String(255))
soyad = Column(String(255))
email = Column(String(255))
kayit_tarihi = Column(DateTime, default=datetime.utcnow)
# Tabloları oluştur
Base.metadata.create_all(bind=engine)
# Kullanım örneği
db = SessionLocal()
# Yeni müşteri ekleme
yeni_musteri = Musteri(ad="Can", soyad="Bekir", email="can@example.com")
db.add(yeni_musteri)
db.commit()
db.refresh(yeni_musteri)
# Müşterileri sorgulama
musteriler = db.query(Musteri).all()
for musteri in musteriler:
print(musteri.ad, musteri.soyad)
db.close()5. Güvenlik Önlemleri
SQL Injection'dan Korunma: Her zaman parametreli sorgular kullanın:
# YANLIŞ - SQL Injection riski
cursor.execute(f"SELECT * FROM users WHERE username = '{username}' AND password = '{password}'")
# DOĞRU
cursor.execute("SELECT * FROM users WHERE username = %s AND password = %s", (username, password))Bağlantı Bilgilerini Güvende Tutma: Bağlantı bilgilerini kod içinde saklamayın, ortam değişkenlerini kullanın:
import os
from dotenv import load_dotenv
load_dotenv()
connection = mysql.connector.connect(
host=os.getenv('DB_HOST'),
database=os.getenv('DB_NAME'),
user=os.getenv('DB_USER'),
password=os.getenv('DB_PASSWORD')
)Bağlantı Havuzu Kullanma: Yüksek trafikli uygulamalarda bağlantı havuzu kullanın:
from mysql.connector import pooling
connection_pool = pooling.MySQLConnectionPool(
pool_name="my_pool",
pool_size=5,
host='localhost',
database='veritabani_adi',
user='kullanici_adi',
password='sifre'
)
# Kullanım
connection = connection_pool.get_connection()
cursor = connection.cursor()
# işlemler...
cursor.close()
connection.close() # Bağlantıyı havuza geri verirSonuç
Python'da MySQL ile çalışmak için birden fazla yöntem mevcuttur. Temel seviyede işlemler için mysql-connector-python veya PyMySQL kullanabilirsiniz. Daha karmaşık projelerde ise SQLAlchemy gibi ORM araçları size büyük kolaylık sağlayacaktır.
Hangi yöntemi seçerseniz seçin, güvenlik önlemlerini almayı ve kaynakları doğru yönetmeyi (bağlantıları kapatma gibi) unutmayın.
Hiç yorum yok:
Yorum Gönder