I'm using MySQLdb module in Python 2.7 with a MariaDB database. I want to know how would be the proper way of using a database across multiple modules. I have this example in which I try to insert elements from another function into the database. I'm getting OperationalError: (1046, 'No database selected')
Edit: Here is the corrected code (1, 2). Thanks. Know I would like a working example like this one with dependency injection.
This is the module in which I want to handle the database.
# test.py
import MySQLdb
import traceback
import test2 as insert_module
from warnings import filterwarnings
# Ignore MySQL `table already exists` warnings
filterwarnings ('ignore', category = MySQLdb.Warning)
# Create database object to keep it open as global variable
class MyDB (object):
connection = None
cursor = None
# Open database connection
def connect (self):
self.connection = MySQLdb.connect ()
self.cursor = self.connection.cursor ()
def execute (self, sql, *args):
try:
self.cursor.execute (sql, *args)
self.connection.commit ()
except MySQLdb.Error, e:
print (traceback.format_exc())
self.connection.rollback ()
def query (self, sql, *args):
try:
self.execute (sql, *args)
# Reopen database connection
except ( AttributeError, MySQLdb.OperationalError ):
self.connect ()
self.execute (sql, *args)
def disconnect (self):
self.connection.close ()
db = MyDB ()
def createDatabase ():
db.query ("CREATE DATABASE IF NOT EXISTS Product")
db.query ("USE Product")
sql = """CREATE TABLE IF NOT EXISTS `ProductColor` (
`ProductID` VARCHAR(20) PRIMARY KEY,
`ColorID` VARCHAR(20)
)"""
db.query (sql)
def insertProductColor (*args):
sql = """INSERT INTO `ProductColor` VALUE (%s, %s)"""
db.query (sql, args)
def main ():
createDatabase ()
insert_module.processListOfProductColors ()
if __name__ == "__main__":
main ()
db.disconnect ()
This is the module from which I want to insert the products.
#test2.py
import test as db_module
def processListOfProductColors ():
db_module.insertProductColor ("cup", "blue")