Python库之MySQLdb介绍

来源:互联网 发布:直通车怎么开淘宝 编辑:程序博客网 时间:2024/06/16 00:25
今天想用python给公司写个小的程序,实现从mysql中读取数据,update等操作,结果发现目前python竟然没有官方库,搜了一下,找到个应用比较多的,今天的主角–“MySQLdb”
网址:http://mysql-python.sourceforge.net/

使用手册:http://mysql-python.sourceforge.net/MySQLdb.html

我的博客:http://www.paulwangblog.com

其实就是对mysql的 C API进行了封装,支持事务(5.0以上,且用InnoDB方式)
使用步骤:
1.安装python
2.根据python的版本下载MySQLdb的安装包(也可以自己编译),注意一定要对应python的版本,3.2的安装包是MySQL-python-1.2.3.win32-py3.2.exe,自己可以对应搜索下,有一个比较全的网站,但是我找不到了

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()


原创粉丝点击