Created
January 13, 2023 13:00
-
-
Save Skifry/f44bdf7bfc75202947738e0b6813038d to your computer and use it in GitHub Desktop.
MySQL DB integration class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pymysql import connect as db_connect | |
import pymysql.cursors | |
class DBConnection(): | |
hostname = "10.66.66.27" | |
username = "babirusa" | |
password = "babirusa" | |
db = 'babirusa' | |
def __enter__(self): | |
self.connection = db_connect(host=self.hostname, | |
user=self.username, | |
password=self.password, | |
database=self.db, | |
cursorclass=pymysql.cursors.DictCursor) | |
self.cursor = self.connection.cursor() | |
return self | |
def read_once(self, query, params): | |
self.cursor.execute(query, params) | |
return self.cursor.fetchone() | |
def read_all(self, query, params): | |
self.cursor.execute(query, params) | |
return self.cursor.fetchall() | |
def write_query(self, query, params): | |
self.cursor.execute(query, params) | |
self.connection.commit() | |
def __exit__(self, type, value, traceback): | |
self.connection.close() | |
# прочитать одну запись из дб | |
with DBConnection() as db: | |
result = db.read_once("SELECT * FROM table WHERE id = %s AND owner = %s", ("параметры", "параметры")) | |
id = result["id"] | |
owner = result["owner"] | |
# прочитать все записи из дб | |
with DBConnection() as db: | |
results = db.read_all("SELECT * FROM table WHERE id = %s AND owner = %s", ("параметры", "параметры")) | |
for result in results: | |
id = result["id"] | |
owner = result["owner"] | |
# записать в дб | |
with DBConnection() as db: | |
db.write_query("INSERT INTO table (id, owner) VALUES (%s, %s)", ("параметры", "параметры")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment