• 自己实现的一个针对MySQL的Python 数据库组建


    #-*- coding:utf8 -*-
    import MySQLdb
    import dbhash
    
    class DbManager():
        dbConf = {
            'host': 'localhost',
            'user': '用户',
            'password': '数据库密码',
            'db_name': '数据库名称',
            'port': 3306,
            'charset': 'utf8',
        }
    
    
        def connect(self):          #获取数据库连接
            return MySQLdb.connect(self.dbConf['host'], user=self.dbConf['user'], passwd=self.dbConf['password'],
                db=self.dbConf['db_name'], charset=self.dbConf['charset'])
    
        def query(self, sql):
            connect = self.connect()
            cur = connect.cursor()
            cur.execute(sql)
            index = cur.description
            result = []
            for res in cur.fetchall():
                row = {}
                for i in range(len(index)-1):
                    row[index[i][0]] = res[i]
                result.append(row)
            connect.close()
            return result
    
        def update(self, sql):
            connect = self.connect()
            cur = connect.cursor()
            result = cur.execute(sql)
            connect.commit()
            connect.close()
            return result
    
        def insert(self, sql):
            connect = self.connect()
            cur = connect.cursor()
            result = cur.execute(sql)
            connect.commit()
            connect.close()
            return result
    
        def delete(self, sql):
            connect = self.connect()
            cur = connect.cursor()
            result = cur.execute(sql)
            connect.commit()
            connect.close()
            return result
    
        def count(self, sql):
            connect = self.connect()
            cur = connect.cursor()
            result = cur.execute(sql)
            connect.close()
            return result

    该组件主要是简单封装了数据查询的地功能,亮点是

    query(self, sql)方法查询出来的数据都是以数据库字段名称为键名的字典的集合:

    例:

        sql = 'select id,userName,password from user limit 5; ';
        res = DbManager().query(sql);
        for r in res:
           print r

    结果:

    {'userName': u'SuperAdmin', 'id': 1L}
    {'userName': u'test', 'id': 2L}
    {'userName': u'\u5f20\u5803', 'id': 3L}
    {'userName': u'\u9648\u6d32\u9f99', 'id': 4L}
    {'userName': u'ddd', 'id': 6L}

    如果把print r 改成  print r['id'],输出结果将为:

  • 相关阅读:
    Android之json解析
    关闭Android/iPhone浏览器自动识别数字为电话号码
    CSS 公共样式摘自万能的度娘
    前端必备:六款CSS工具让代码充满魅力
    移动端JS 触摸事件基础
    height:100%和height:auto的区别
    线程之生产汽车与购买汽车
    SAXCreateXMLDocument
    DOM方式创建XML文件
    java快捷键
  • 原文地址:https://www.cnblogs.com/nackman/p/python.html
Copyright © 2020-2023  润新知