zoukankan      html  css  js  c++  java
  • 使用MySQLdb操作Mysql数据库

    MySQLdb简介

    MySQL是一个小型关系型数据库管理系统,开发者为瑞典MySQLAB公司。在2008年1月16号被Sun公司收购。目前MySQL被广泛地应用在Internet上的中小型网站中。由于其体积小、速度快、总体拥有成本低,尤其是开放源码这一特点,许多中小型网站为了降低网站总体拥有成本而选择了MySQL作为网站数据库。同样MySQLdb也是Python 连接 MySQL 的一个第三方模块

    MySQLdb安装

    window下安装

    1、在http://www.codegood.com/downloads下载MySQLdb相对应的执行文件进行安装就可以

    2、利用pip进行安装(http://www.lfd.uci.edu/~gohlke/pythonlibs/)安装MySQLdb之前先要安装wheel,执行pip install wheel命令进行安装,

    然后,执行pip install MySQL_python-1.2.5-cp27-none-win32.whl    ,如果是安装64位的,需要把这个文件名改为“MySQL_python-1.2.5-cp27-none-any.whl”

    linux下安装

    1、利用pip进行安装

     pip install MySQL-python 

    在安装的过程中可能会报错,如下图(可能是依赖没安装,以下就是安装依赖的部分)

    1>安装 mysql-devel(这个过程中还可能报错)

    yum -y install mysql-devel
    

    2>添加源

    cd /etc/yum.repos.d/ 
    
    rpm -ivh http://repo.mysql.com/mysql57-community-release-el7-8.noarch.rpm 

    3>继续安装依赖

    yum install yum-utils
    yum install libmysqlclient-dev
    
    yum-complete-transaction
    

    4>最后安装

    yum -y install mysql-devel
    
    yum install python-devel

    2、源码安装

    参考:http://www.cnblogs.com/zengkefu/p/5624837.html

    MySQLdb使用

    引入 API 模块。
    获取与数据库的连接。
    执行SQL语句和存储过程。
    关闭数据库连接。
    

    一、连接数据库

    MySQLdb提供了connect方法用来和数据库建立连接,接收数个参数,返回连接对象:

    conn=MySQLdb.connect(host="localhost",user="root",passwd="jb51",db="test",charset="utf8")
    

    比较常用的参数包括(更多关于参数的信息可以查这里 http://mysql-python.sourceforge.net/MySQLdb.html):

    host:数据库主机名.默认是用本地主机
    user:数据库登陆名.默认是当前用户
    passwd:数据库登陆的秘密.默认为空
    db:要使用的数据库名.没有默认值
    port:MySQL服务使用的TCP端口.默认是3306
    charset:数据库编码

    二、简单使用

    import MySQLdb
    #连接数据库
    db=MySQLdb.connect(host="localhost",user="root",passwd="",db="apwd_center",charset="utf8")
    # 使用cursor()方法获取操作游标
    cursor = db.cursor()
    #形成sql语句
    sql = 'select * from apk_download_info limit 10'
    # 使用execute方法执行SQL语句
    cursor.execute(sql)
    # 使用 fetchone() 方法获取一条数据库。
    data = cursor.fetchone()
    # 关闭数据库连接
    db.close()
    

    三、在工作中为了方便运用,可以用类实现数据库操作

    #!/usr/bin/python
    # coding:utf-8
    
    import MySQLdb
    
    class SQLdb(object):
        '''
        支持插入、更新、删除、查询(获取所有)操作
        在不需要的时候需要手动释放db资源
        '''
    
        def __init__(self, host=None, username=None, password=None, dbname=None):
            if host is None and username is None and password is None and dbname is None:
                self.host = "localhost"
                self.username = "root"
                self.password = "123456"
                self.dbname = "apwd_center"
            else:
                self.host = host
                self.username = username
                self.password = password
                self.dbname = dbname
            self.max_connect_cnt = 20
            self.__conndb()
            self.Error = False
    
        # 连接数据库
        def __conndb(self):
            connect_cnt = 0
            while True:
                try:
                    self.db = MySQLdb.connect(self.host, self.username, self.password, self.dbname, charset='utf8')
                except Exception, e:
                    # 当连接过多的时候或者其他异常的时候则sleep 1秒则重新连接
                    # time.sleep(1)	#这个可以注释掉
                    connect_cnt += 1
                    if connect_cnt < self.max_connect_cnt:
                        pass
                    else:
                        raise e
                else:
                    break
            self.cursor = self.db.cursor()
    
        # 装饰器函数保证更新数据的时候,连接OK,如果连接不正确重新连接
        def reconnectdb(func):
            def wrapfunc(self, sql=''):
                try:
                    self.db.ping()
                except:
                    self.__conndb()
                self.Error = False
                return  func(self, sql)
            return wrapfunc
    
        # 插入数据
        @reconnectdb
        def insertdb(self, sql):
            try:
                self.cursor.execute(sql)
                self.db.commit()
            except Exception, e:
                # Rollback in case there is any error
                print "Error: unable to insertdb!"
                self.db.rollback()
                self.Error = True
    
        # 更新数据
        @reconnectdb
        def updatedb(self, sql):
            try:
                self.cursor.execute(sql)
                self.db.commit()
            except Exception, e:
                # Rollback in case there is any error
                print "Error: unable to updatedb!"
                self.db.rollback()
                self.Error = True
    
        # 获取数据
        @reconnectdb
        def fechdb(self, sql):
            try:
                self.cursor.execute(sql)
                results = self.cursor.fetchall()
                return results
            except Exception, e:
                print "Error: unable to fecth data"
                self.Error = True
    
        # 删除数据
        @reconnectdb
        def deldb(self, sql):
            try:
                self.cursor.execute(sql)
                self.db.commit()
            except:
                # Rollback in case there is any error
                print "Error: unable to deldb!"
                self.db.rollback()
                self.Error = True
    
        # 关闭数据
        def closedb(self):
            try:
                self.db.close()
            except:
                print "数据库已关闭,无需关闭"
    
    
    if __name__ == '__main__':
    
        db = SQLdb()
        sql = "select * from phishing_info where phishing_site = 'http://wap.inbch.cc';"
        result = db.fechdb(sql)
        print result
        print len(result)
  • 相关阅读:
    c++中static的使用
    sublime3 ctl+b无效
    Maximum Subarray
    Find the Duplicate Number
    Reverse Linked List
    c++ primer 2 变量和基本类型
    Single Number II
    Roman to Integer & Integer to Roman
    Search Insert Position
    Unique Binary Search Trees II
  • 原文地址:https://www.cnblogs.com/luxiaojun/p/6973123.html
Copyright © 2011-2022 走看看