Created
August 3, 2021 19:39
-
-
Save omarjcero/5be207b744c35ac0806f28be9dbb07f9 to your computer and use it in GitHub Desktop.
MySQL simple class to handle queries in python
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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import pymysql | |
class ConexionMySQL: | |
def __init__(self, host, user, pwd, dbname): | |
self.db_host = host | |
self.db_user = user | |
self.db_pass = pwd | |
self.db_name = dbname | |
self.db = None | |
self.cursor = None | |
self.connect() | |
def __del__(self): | |
try: | |
print(".closing conn.") | |
self.cursor.close() | |
self.db.close() | |
except Exception as e: | |
print(str(e)) | |
def connect(self): | |
try: | |
self.db = pymysql.connect(host=self.db_host, user=self.db_user, passwd=self.db_pass, db=self.db_name) | |
self.cursor = self.db.cursor() | |
except pymysql.Error as err: | |
print(err) | |
def query(self, query): | |
try: | |
self.cursor.execute(query) | |
self.cursor.commit() | |
except pymysql.Error as err: | |
print(str(err)) | |
def select(self, query): | |
try: | |
self.cursor.execute(query) | |
except Exception as e: | |
print(str(e)) | |
return self.cursor.fetchall() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment