Python, sqlite3 ile tablo oluşturmak

Merhaba arkadaşlar sqlite3 ile tablo oluşturmak istiyorum.

sorgu  = "create Table if not exists Onbir_A (İsim_Soyisim TEXT, Numara TEXT)"

Bu, kullandığım yöntem ama ben istiyorum ki tablonun adı, input ile alınsın. (?)'lerini nasıl yerleştirmem lazım?

Bu da kodlarımın hepsi, bir class içinde tanımlanmış durumda.

    def bağlantı_oluştur(self):

        self.bağlantı = sqlite3.connect("Dershane.db")
        self.cursor = self.bağlantı.cursor()

        sorgu = "create Table if not exists Onbir_A (İsim_Soyisim TEXT, Numara TEXT)"

        self.cursor.execute(sorgu)
        self.bağlantı.commit()

Merhaba,

Şöyle yapabilirsiniz:

def sutun_olustur(sayi: int):
    return [input(f"{i + 1}. Sütunun İsmi: ") for i in range(sayi)]


sorgu = f"CREATE TABLE IF NOT EXISTS {input('Tablo İsmi: ')} " \
        f"({', '.join(sutun_olustur(sayi=2))})"
print(sorgu)

Örnek:

Tablo İsmi: CUSTOMER
1. Sütunun İsmi: Name TEXT
2. Sütunun İsmi: Email TEXT
CREATE TABLE IF NOT EXISTS CUSTOMER (Name TEXT, Email TEXT)
1 Beğeni

Teşekkürler inceleyeceğim

Abi önerim def vs kullanırken türkçe karakter kullanmamaya çalış çok hata aldım bundan dolayı

1 Beğeni

Tablo isimleri parametre (?) olamiyor. Dinamik tablo isimleri kotu aliskanlik zaten. Yapacaksan en azindan escape veya verify etmeye calis.

2 Beğeni

@aib’in söylediğiyle alakalı bir postu sizinle paylaşayım:

One thing to be mindful of is the source of the value for the table name. If that comes from an untrusted source, e.g. a user, then you need to validate the table name to avoid potential SQL injection attacks. One way might be to construct a parameterised query that looks up the table name from the DB catalogue:

import sqlite3

def exists_table(db, name):
   query = "SELECT 1 FROM sqlite_master WHERE type='table' and name = ?"
   return db.execute(query, (name,)).fetchone() is not None
1 Beğeni