本文共 2511 字,大约阅读时间需要 8 分钟。
今天想用python给公司写个小的程序,实现从mysql中读取数据,update等操作,结果发现目前python竟然没有官方库,搜了一下,找到个应用比较多的,今天的主角–“MySQLdb”使用手册:http://mysql-python.sourceforge.net/MySQLdb.html
我的博客:
其实就是对mysql的 C API进行了封装,支持事务(5.0以上,且用InnoDB方式)3.写应用,下面是我封装的一个mysql操作类,支持事务,代码请参考,时间关系我并没有加注释,不过应该很好懂,你也可以根据自己需求封装一下
#===============================================================================# -*- coding: utf-8 -*-#MySQLdb封装类#author:paul wang#===============================================================================import MySQLdb as mdbclass myMySQL: def connect(self,host="localhost",user="root",pwd="",database="",autocommit=False): try: self.isConnect = False self.conn = mdb.connect( host, user, pwd, database); self.isConnect = True self.cursor = self.conn.cursor() self.cursor.execute("SELECT VERSION()") data = self.cursor.fetchone() if autocommit: self.conn.autocommit(True) else: self.conn.autocommit(False) except mdb.Error as e: print ( "Connect Error %d: %s" % (e.args[0],e.args[1]) ) print ( "Database version : %s " % data ) def close(self): try: self.cursor.close() self.conn.close() except mdb.Error as e: print ( "Close Error %d: %s" % (e.args[0],e.args[1]) ) def excute(self,sql=""): try: self.cursor.execute(sql) except mdb.Error as e: print ( "Excute Error %d: %s" % (e.args[0],e.args[1]) ) print ( "Excute sql= %s" % sql ) def getrows(self,sql): try: self.excute(sql) rows = self.cursor.fetchall() return rows except mdb.Error as e: print ( "getrows Error %d: %s" % (e.args[0],e.args[1]) ) def selectDB(self,dbName): self.conn.select_db(dbName) def commit(self): self.conn.commit() def rollback(self): self.conn.rollback() def setautocommit(self,auto=False): self.conn.autocommit(auto) def isConnected(self): return self.isConnect#下面是测试代码#db = myMySQL()#db.connect( "localhost","root","","drupal",False )#db.setautocommit(False)#db.excute("insert into test values(2)")#db.rollback()#rows = db.getrows("select * from test where 1 = 1 ")#print( rows )#db.close()
转载地址:http://rggdi.baihongyu.com/