Python实现一个简单的MySQL类

yipeiwu_com5年前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批量修改文件名的实现代码

#coding:utf-8 #批量修改文件名 import os import re import datetime re_st = r'(\d+)\+\s?\((...

Python中的字典与成员运算符初步探究

Python中的字典与成员运算符初步探究

Python元字典 字典(dictionary)是除列表以外python之中最灵活的内置数据结构类型。列表是有序的对象结合,字典是无序的对象集合。 两者之间的区别在于:字典当中的元素是通...

在Python的Django框架中用流响应生成CSV文件的教程

在Django里,流式响应StreamingHttpResponse是个好东西,可以快速、节省内存地产生一个大型文件。 目前项目里用于流式响应的一个是Eventsource,用于改善跨系...

Python smtplib实现发送邮件功能

本文实例为大家分享了Python smtplib发送邮件功能的具体代码,供大家参考,具体内容如下 解决之前版本的问题,下面为最新版 #!/usr/bin/env python #...

详解Python读取yaml文件多层菜单

需要用到的Python知识点 Python的对象属性方法; 用到字典{key:value}值的提取; 列表的增加; if循环结合break的使用; yaml文件读取...