N
n00b
greetings,
i need to log to the db directly and wrote a little script to do so.
since i'm pretty new to python,
i was wondering if a) you could review the enclosed code and b)
provide suggestions to harden to code to turn it into a more general,
broadly reusable class.
thank you very much.
import sys
import MySQLdb
class DBLogger(object):
def __init__(self):
self.db_name = 'xxx'
self.db_host = '127.0.0.1'
self.db_table = 'yyy'
self.db_uname = 'root'
self.db_passwd = ''
self.db_port = 3306
self.db = None
self.cur = None
self.sql = 'INSERT INTO %s' %self.db_table + ' VALUES(null, NOW
(), %s)'
def openDb(self):
try:
self.db = MySQLdb.connect(host = self.db_host,
user = self.db_uname,
passwd = self.db_passwd,
db = self.db_name,
)
self.cur = self.db.cursor()
return self.db, self.cur
except Exception, e:
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
print e[0], e[1]
sys.exit(1)
def closeDb(self):
self.cur.close()
self.db.close()
def write(self, string):
s = string.strip('\n')
if not s=='':
self.openDb()
self.cur.execute(self.sql, (s))
self.db.commit()
self.closeDb()
dbl = DBLogger()
sys.stdout = dbl
sys.stderr = dbl
#a = 'test string'
#dbl.write(a)
print 'a b c '
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
thanks again for your time
i need to log to the db directly and wrote a little script to do so.
since i'm pretty new to python,
i was wondering if a) you could review the enclosed code and b)
provide suggestions to harden to code to turn it into a more general,
broadly reusable class.
thank you very much.
import sys
import MySQLdb
class DBLogger(object):
def __init__(self):
self.db_name = 'xxx'
self.db_host = '127.0.0.1'
self.db_table = 'yyy'
self.db_uname = 'root'
self.db_passwd = ''
self.db_port = 3306
self.db = None
self.cur = None
self.sql = 'INSERT INTO %s' %self.db_table + ' VALUES(null, NOW
(), %s)'
def openDb(self):
try:
self.db = MySQLdb.connect(host = self.db_host,
user = self.db_uname,
passwd = self.db_passwd,
db = self.db_name,
)
self.cur = self.db.cursor()
return self.db, self.cur
except Exception, e:
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
print e[0], e[1]
sys.exit(1)
def closeDb(self):
self.cur.close()
self.db.close()
def write(self, string):
s = string.strip('\n')
if not s=='':
self.openDb()
self.cur.execute(self.sql, (s))
self.db.commit()
self.closeDb()
dbl = DBLogger()
sys.stdout = dbl
sys.stderr = dbl
#a = 'test string'
#dbl.write(a)
print 'a b c '
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
thanks again for your time