简单封装了python中使用MySQL数据的操作。
#Python连接MySQL数据库
import MySQLdb
class Getdb():
def __init__(self, host, user, passwd, db, charset):
try:
self.conn = MySQLdb.connect(host='host',user='user',passwd='passwd',db='db',charset="charset")
self.cursor = self.conn.cursor()
except Exception, e:
sys.exit()
def selectInfo(self,sql):
try:
n = self.cursor.execute(sql)
if n != 0:
data = self.cursor.fetchall()
else:
data = "N-DATA"
self.logger.log('warn', 'No Data found from DB!, SQL:<' + sql + '>')
except Exception, e:
data = "S-ERROR"
return data
def selectInfoWithArgs(self,sql,param):
try:
n = self.cursor.execute(sql,param)
if n != 0:
data = self.cursor.fetchall()
else:
data = "N-DATA"
except Exception:
data = "S-ERROR"
return data
def executeSQLWithArgs(self,sql,param):
try:
self.cursor.execute(sql,param)
self.conn.commit()
result = "I-SUCESS"
except Exception, e:
result = "I-FAIL"
return result
def executeSQL(self,sql):
try:
self.cursor.execute(sql)
self.conn.commit()
result = "I-SUCESS"
except Exception, e:
result = "I-FAIL"
return result
def close(self):
''' 关闭连接 '''
self.cursor.close()
self.conn.close()
使用:
conn = DBManager.Getdb(host, user, passwd, db, charset)
data = conn.selectInfo(selectsql)
#param = (arg1, arg2)
#data = conn.selectInfoWithArgs(selectsql, param)
conn.close()
if data != “S-ERROR” and data != “N-DATA”:
for d in data:
func()
ret = conn.executeSQL(updateSql)
#param = (arg1, arg2)
#data = conn.executeSQLWithArgs(updateSql, param)
if ret != “I-SUCESS”:
logger.error(“DB operate failed, result:%s” % ret)