Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Last active September 10, 2024 14:06
Show Gist options
  • Save xeoncross/494947640a7dcfe8d91496988a5bf325 to your computer and use it in GitHub Desktop.
Save xeoncross/494947640a7dcfe8d91496988a5bf325 to your computer and use it in GitHub Desktop.
Example database class for wrapping mysql-connector for python
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()
@xeoncross
Copy link
Author

Here is an example of how you can use the mysql-connector-python library to connect to a MySQL database and issue a query:

import mysql.connector

# Connect to the database
cnx = mysql.connector.connect(user='<username>',
                              password='<password>',
                              host='<hostname>',
                              database='<database>')

# Create a cursor object
cursor = cnx.cursor()

# Define the query
query = "SELECT * FROM <table>"

# Execute the query
cursor.execute(query)

# Fetch the results
results = cursor.fetchall()

# Iterate over the results and print each row
for row in results:
    print(row)

# Close the cursor and connection
cursor.close()
cnx.close()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment