I am trying to create a class that holds all my database operations. I would like to initiate a MySQL connection whenever this class is called, perform whatever db operations it needs to do and close it after it's done.
This is what I have so far:
import MySQLdb
class Database_Test(object):
def __init__(self, db_local):
self.db_conn = MySQLdb.connect(**db_local)
self.db_cursor = self.db_conn.cursor()
def get_row(self, sql, data = None):
self.db_cursor.execute(sql)
self.resultset = self.db_cursor.fetchall()
self.db_cursor.close()
return self.resultset
# Close db connection something like this?
# db_conn.close()
db_config = {
'host':"127.0.0.1", # database host
'port': 3306, # port
'user':"root", # username
'passwd':"admin", # password
'db':"test", # database
'charset':'utf8' # charset encoding
}
sql = "SELECT * FROM mytest LIMIT 10"
test = Database_Test(db_config)
test.get_row(sql)
print(test)
This is what I get:
<__main__.Database_Test object at 0x00774BF0>
Somehow this is not what I was expecting to get as I was expecting to get some records from the database.