Python实现一个简单的MySQL类

yipeiwu_com6年前Python基础

本文实例讲述了Python实现一个简单的MySQL类。分享给大家供大家参考。

具体实现方法如下:

复制代码 代码如下:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Created on 2011-2-19
# @author: xiaoxiao
import MySQLdb
import sys
__all__ = ['MySQL']
class MySQL(object):
    '''
    MySQL
    '''
    conn = ''
    cursor = ''
    def __init__(self,host='localhost',user='root',passwd='root',db='mysql',charset='utf8'):
      
        """MySQL Database initialization """
        try:
            self.conn = MySQLdb.connect(host,user,passwd,db)
        except MySQLdb.Error,e:
            errormsg = 'Cannot connect to server\nERROR (%s): %s' %(e.args[0],e.args[1])
            print errormsg
            sys.exit()
          
        self.cursor = self.conn.cursor()
      
    def query(self,sql):
        """  Execute SQL statement """
        return self.cursor.execute(sql)
  
    def show(self):
        """ Return the results after executing SQL statement """
        return self.cursor.fetchall()
             
    def __del__(self):
        """ Terminate the connection """
        self.conn.close()
        self.cursor.close()
      
#test
if __name__ == '__main__':
  
    mysql = MySQL(host=localhost,passwd='test',db='mysql')
    mysql.query('select * from users')
    result = mysql.show()
    print len(result)
    print result[1]

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Python 互换字典的键值对实例

1.zip dic = {'a':1, 'b':2, 'c':3} dic_new = dict(zip(dic.values(), dic.keys())) print(dic_n...

python读取大文件越来越慢的原因与解决

python读取大文件越来越慢的原因与解决

背景: 今天同事写代码,用python读取一个四五百兆的文件,然后做一串逻辑上很直观的处理。结果处理了一天还没有出来结果。问题出在哪里呢? 解决: 1. 同事打印了在不同时间点的时间,在...

Python 实现还原已撤回的微信消息

Python 实现还原已撤回的微信消息

导包效果展示 以下截图显示的撤回消息类型依次是文字消息、微信自带表情、图片、语音、定位地图、名片、公众号文章、音乐、视频。有群里撤回的,也有个人号撤回的。 图文来源:http://kk...

Python内置函数OCT详解

英文文档: 复制代码 代码如下:oct ( x ) Convert an integer number to an octal string. The result is a valid...

pytorch 实现张量tensor,图片,CPU,GPU,数组等的转换

1, 创建pytorch 的Tensor张量: torch.rand((3,224,224)) #创建随机值的三维张量,大小为(3,224,224) torch.Tensor([...