[[:oktatas:programozás:python:adatbázis|< Adatbázis]]
====== Interfész használata ======
* **Szerző:** Sallai András
* Copyright (c) 2020, Sallai András
* Licenc: [[https://creativecommons.org/licenses/by-sa/4.0/|CC BY-SA 4.0]]
* Web: https://szit.hu
===== Bevezetés =====
A Python nyelv nem támogatja az interfész használatát, de használhatunk
egy interface modult.
===== Employee.py =====
class Employee:
def __init__(self, id, name, city, salary):
self.id = id
self.name = name
self.city = city
self.salary = salary
===== iDatabase.py =====
from interface import Interface
class iDatabase(Interface):
def connectDb(self):
pass
===== Mariadb.py =====
from interface import implements
from iDatabase import iDatabase
from mariadb import connect, Error
import sys
class Mariadb(implements(iDatabase)):
def tryConnectDb(self):
print('Működik')
config = {
'host': 'localhost',
'user': 'feherbt',
'password': 'titok'
}
conn = connect(**config, database='feherbt')
return conn
def connectDb(self):
try:
conn = self.tryConnectDb()
except Error as err:
print('Hiba! A kapcsolódás sikertelen!')
print(err, file=sys.stderr)
return conn
if __name__ == '__main__':
Mariadb().connectDb()
===== DataManager.py =====
A "database: iDatabase" állítás jelzi, hogy iDatabase paramétert várunk, de
maga a Python nyelv nem követeli meg, hogy ténylegesen azt adjuk át paraméterként
a hívás helyén.
from iDatabase import iDatabase
from Mariadb import Mariadb
from Employee import Employee
class DataManager:
def __init__(self, database: iDatabase):
self.database = database
def getEmployees(self):
conn = self.database.connectDb()
cur = conn.cursor()
sql = 'select * from employees'
cur.execute(sql)
employeeList = []
for (id, name, city, salary) in cur:
employee = Employee(id, name, city, salary)
employeeList.append(employee)
return employeeList
def insertEmployee(self, employee: Employee):
conn = self.database.connectDb()
cur = conn.cursor()
sql = """
insert into employees
(name, city, salary) values
(?, ?, ?)
"""
values = (employee.name, employee.city, employee.salary)
cur.execute(sql, values)
conn.commit()
conn.close()
if __name__ == '__main__':
data_manager = DataManager(Mariadb())
===== program01.py =====
from DataManager import DataManager
from Mariadb import Mariadb
from Employee import Employee
data_manager = DataManager(Mariadb())
employee = Employee(0, 'Reke Imre', 'Szeged', 4740000)
data_manager.insertEmployee(employee)
employees = data_manager.getEmployees()
for employee in employees:
print(employee.name)