Python Mysql类

Python支持Mysql的库

# yum -y install  MySQL-python

import MySQLdb

mysql_instance = "";
class MySQLHelper:
	def __init__(self,host,user,password,db_name,charset="utf8"):
		self.host = host
		self.user = user
		self.password = password
		self.db_name = db_name
		self.charset = charset
		try:
			self.conn = MySQLdb.connect(host=self.host,user=self.user,passwd=self.password,db=self.db_name, charset=self.charset)
		except:
			print("Mysql Connect Error ")
			sys.exit(0)

	def update_sql_cmd(self,sql_cmd):
		self.cur = self.conn.cursor()
		try :
			self.cur.execute(sql_cmd)
			self.conn.commit()
			self.cur.close()
			return True
		except Exception, e:
			print "[MYSQL ERROR] : %s"%sql_cmd
			self.cur.close()
			return False

	def run_sql_cmd(self,sql_cmd):
		try :
			self.cur = self.conn.cursor()
			self.cur.execute(sql_cmd)
			res = self.cur.fetchall()
			self.cur.close()
			return res
		except Exception, e:
			print "[MYSQL ERROR] : %s"%sql_cmd
			self.cur.close()
			return False

	def close(self):
		self.conn.close()

def mysql_init():
	'''connect to mysql database opencdn'''
	try:
		global mysql_instance
		mysql_instance = MySQLHelper(mysql_host,mysql_username,mysql_password,mysql_dbname)
	except Exception, e:
		print("Mysql Error %d: %s" % (e.args[0], e.args[1]))
		sys.exit(1)

update_sql_cmd()可以对mysql进行插入操作
run_sql_cmd()可以对mysql查询操作并且返回二元组

标签:Linux, Python

评论已关闭