前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python操作Mysql类

Python操作Mysql类

作者头像
苦咖啡
发布2018-04-28 14:04:55
1.1K0
发布2018-04-28 14:04:55
举报
文章被收录于专栏:我的博客我的博客
代码语言:javascript
复制
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
from warnings import filterwarnings
filterwarnings('error', category = MySQLdb.Warning)

class MySQL :

    __conn = None
    __cursor = None

    def __init__(self, host, user, passwd, db ,port = 3306, charset = 'utf8'):
        try:
            self.__conn = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db, port=port,charset=charset)
            self.__cursor = self.__conn.cursor()
        except MySQLdb.Warning, w:
            print "警告信息 %s" % str(w)
        except MySQLdb.Error, e:
            print "错误信息 %d %s" % (e.args[0], e.args[1])
    #插入数据
    def insert(self, table, dict):
        if len(dict) > 0 :
            keys = dict.keys()
            keyStr = ""
            valStr = ""
            for key in keys:
                keyStr += "`" + str(key) + '`,'
                valStr += "'" + str(dict[key]) + "',"
            keyStr = keyStr.rstrip(',')
            valStr = valStr.rstrip(',')
            sql = "INSERT INTO `" + str(table) + "` (" + keyStr + ") VALUES " + "("+ valStr +")"
            print '执行语句: %s' % sql
            try :
                self.__cursor.execute(sql)
                #lastId = self.__conn.insert_id() #这个一定要在commit之前!!!
                lastId = self.__cursor.lastrowid
                self.__conn.commit()
                return lastId
            except:
                print '插入数据异常!执行回滚!'
                self.__conn.rollback()
                return False
        else:
            return False

    #查询一条数据
    def find(self, table, fields = "*", where = "", order = 'id desc'):
        sql = "select " + str(fields) + " from `"+ str(table) + "` "
        if where != '':
            sql += " where " + str(where)
        sql += " order by " + str(order) + " limit 1"
        print "执行语句: %s" % sql
        try:
            self.__cursor.execute(sql)
            return self.__cursor.fetchone()
        except :
            print '查询失败'
            return False

    #查询多条数据
    def fetchall(self, table, fields = "*", where = "", order = "id desc", offset = "0", limit = '20'):
        sql = "select " + str(fields) + " from `" + str(table) + "` "
        if where != '':
            sql += " where " + str(where)
        sql += " order by " + str(order) + " limit " + str(offset) + "," + str(limit)
        print "执行语句: %s" % sql
        try:
            self.__cursor.execute(sql)
            return self.__cursor.fetchall()
        except:
            print '查询失败'
            return False
    # 删除数据
    def delete(self, table, where, limit = 1):
        sql = "delete from `" + str(table) + "` where " + str(where)
        if limit > 0 :
            sql += " limit " + str(limit)
        print '执行语句: %s' % sql
        try:
           self.__cursor.execute(sql)
           self.__conn.commit()
           return True
        except:
            print '删除异常!执行回滚!'
            self.__conn.rollback()
            return False

    # 更新数据
    def update(self, table, dict, where):
        keys = dict.keys()
        updateStr = ""
        for key in keys:
            updateStr += "`" + str(key) + "` = '" + str(dict[key]) +"',"
        updateStr = updateStr.rstrip(',')
        sql = "update `"+str(table)+"` set "+updateStr+" where " + where
        print '执行语句: %s' % sql
        try:
            self.__cursor.execute(sql)
            self.__conn.commit()
            return True
        except:
            print '更新异常!执行回滚!'
            self.__conn.rollback()
    # 释放资源
    def __del__(self):
        self.__cursor.close()
        self.__conn.close()

############################################案例##############

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import time
from MySQL import *
mysql = MySQL(host='10.200.10.203', user='test', passwd='test', db='test')
# print mysql.find('test', 'count(*) as t')
# print mysql.fetchall('test')
# print mysql.delete('test', 'id = 69')
create_time = time.strftime('%Y-%m-%d %H:%M:%S')
content ='这里是测试内容'
name = '测试'
dict = {'name':name,'create_time':create_time,'content':content}
lastid = mysql.insert('test', dict)
name = '测试最新的!!!'
dict = {'name':name}
print mysql.update('test',dict,"id = " + str(lastid))
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016年6月21日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云数据库 MySQL
腾讯云数据库 MySQL(TencentDB for MySQL)为用户提供安全可靠,性能卓越、易于维护的企业级云数据库服务。其具备6大企业级特性,包括企业级定制内核、企业级高可用、企业级高可靠、企业级安全、企业级扩展以及企业级智能运维。通过使用腾讯云数据库 MySQL,可实现分钟级别的数据库部署、弹性扩展以及全自动化的运维管理,不仅经济实惠,而且稳定可靠,易于运维。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档