Last active
September 10, 2024 14:06
-
-
Save xeoncross/494947640a7dcfe8d91496988a5bf325 to your computer and use it in GitHub Desktop.
Example database class for wrapping mysql-connector for 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
import mysql.connector | |
# from mysql.connector import Error | |
# pip3 install mysql-connector | |
# https://dev.mysql.com/doc/connector-python/en/connector-python-reference.html | |
class DB(): | |
def __init__(self, config): | |
self.connection = None | |
self.connection = mysql.connector.connect(**config) | |
def query(self, sql, args): | |
cursor = self.connection.cursor() | |
cursor.execute(sql, args) | |
return cursor | |
def insert(self,sql,args): | |
cursor = self.query(sql, args) | |
id = cursor.lastrowid | |
self.connection.commit() | |
cursor.close() | |
return id | |
# https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-executemany.html | |
def insertmany(self,sql,args): | |
cursor = self.connection.cursor() | |
cursor.executemany(sql, args) | |
rowcount = cursor.rowcount | |
self.connection.commit() | |
cursor.close() | |
return rowcount | |
def update(self,sql,args): | |
cursor = self.query(sql, args) | |
rowcount = cursor.rowcount | |
self.connection.commit() | |
cursor.close() | |
return rowcount | |
def fetch(self, sql, args): | |
rows = [] | |
cursor = self.query(sql, args) | |
if cursor.with_rows: | |
rows = cursor.fetchall() | |
cursor.close() | |
return rows | |
def fetchone(self, sql, args): | |
row = None | |
cursor = self.query(sql, args) | |
if cursor.with_rows: | |
row = cursor.fetchone() | |
cursor.close() | |
return row | |
def __del__(self): | |
if self.connection != None: | |
self.connection.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is an example of how you can use the mysql-connector-python library to connect to a MySQL database and issue a query: