Create database.py
Browse files- database.py +37 -0
database.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sqlite3
|
| 2 |
+
from flask import g
|
| 3 |
+
|
| 4 |
+
def get_db():
|
| 5 |
+
"""Veritabanı bağlantısını oluşturur veya var olanı döndürür"""
|
| 6 |
+
if 'db' not in g:
|
| 7 |
+
g.db = sqlite3.connect('users.db')
|
| 8 |
+
g.db.row_factory = sqlite3.Row # Sözlük formatında sonuçlar
|
| 9 |
+
return g.db
|
| 10 |
+
|
| 11 |
+
def close_db(e=None):
|
| 12 |
+
"""Veritabanı bağlantısını kapatır"""
|
| 13 |
+
db = g.pop('db', None)
|
| 14 |
+
if db is not None:
|
| 15 |
+
db.close()
|
| 16 |
+
|
| 17 |
+
def init_db():
|
| 18 |
+
"""Veritabanını ve tabloları oluşturur"""
|
| 19 |
+
db = get_db()
|
| 20 |
+
cursor = db.cursor()
|
| 21 |
+
|
| 22 |
+
# Kullanıcılar tablosu
|
| 23 |
+
cursor.execute('''
|
| 24 |
+
CREATE TABLE IF NOT EXISTS users (
|
| 25 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 26 |
+
name TEXT NOT NULL,
|
| 27 |
+
score INTEGER DEFAULT 0
|
| 28 |
+
)
|
| 29 |
+
''')
|
| 30 |
+
|
| 31 |
+
# Örnek veriler
|
| 32 |
+
cursor.execute('SELECT COUNT(*) FROM users')
|
| 33 |
+
if cursor.fetchone()[0] == 0:
|
| 34 |
+
cursor.executemany('INSERT INTO users (name, score) VALUES (?, ?)',
|
| 35 |
+
[('Ahmet', 85), ('Mehmet', 92)])
|
| 36 |
+
|
| 37 |
+
db.commit()
|