概述
#coding:utf-8#08年写的importsystry:importMySQLdbexceptImportError:
sys.exit("Exceptions.ImportError: No module named MySQLdbn");classpymysql(object):
conn=Nonedef__init__(self):passdef__del__(self):
self.close()defconnect(self,db_host,db_user,db_password,db_name,db_port=3306,db_charset='utf8'):try:
self.conn=MySQLdb.connect(host=db_host,user=db_user,passwd=db_password,db=db_name,port=db_port,charset=db_charset)
self.__db_host=db_host
self.__db_user=db_user
self.__db_password=db_password
self.__db_name=db_name
self.__db_port=db_port
self.__db_charset=db_charsetreturnTrueexcept:returnFalsedefreconnect(self):try:
self.conn=MySQLdb.connect(host=self.__db_host,user=self.__db_user,passwd=self.__db_password,db=self.__db_name,port=self.__db_port,charset=self.__db_charset)returnTrueexcept:returnFalsedefquote(self,queryString):returnMySQLdb.escape_string(queryString);defquery(self,sql):try:
cursor=self.conn.cursor()
cursor.execute(sql)returncursorexcept:
sys.exit("MySQL Query Error:n"+sql+"n")defexecute(self,sql):try:returnself.conn.cursor().execute(sql)except:
sys.exit("MySQL Query Error:n"+sql+"n")deffetch(self,cursor):returncursor.fetchone()deffetchRow(self,sql):returnself.query(sql).fetchone()deffetchOne(self,sql):try:returnself.query(sql).fetchone()[0]except:returnNonedeffetchAll(self,sql):returnself.query(sql).fetchall()definsert(self,table,row):
sqlArr=[]forkeyinrow.iterkeys():
sqlArr.append("%s='%s'"%(key,row[key],))
sql="insert into"+table+"set"+str.join(",",sqlArr)returnself.execute(sql)defupdate(self,table,row,where):
sqlArr=[]forkeyinrow.iterkeys():
sqlArr.append("%s='%s'"%(key,row[key],))
sql="update"+table+"set"+str.join(",",sqlArr)+"where"+wherereturnself.execute(sql)defclose(self):ifself.conn:
self.conn.close()
最后
以上就是典雅大树为你收集整理的python 封装sql_python mysql封装的全部内容,希望文章能够帮你解决python 封装sql_python mysql封装所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复