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程序设计有所帮助。

相关文章

pandas创建新Dataframe并添加多行的实例

处理数据的时候,偶然遇到要把一个Dataframe中的某些行添加至一个空白的Dataframe中的问题。 最先想到的方法是创建Dataframe,从原有的Dataframe中逐行筛选出指...

python实现雨滴下落到地面效果

python实现雨滴下落到地面效果

本文实例为大家分享了python实现雨滴下落到地面效果的具体代码,供大家参考,具体内容如下 本程序在Windows 64位操作系统下,安装的是Anaconda3-4.2.0 impo...

关于pandas的离散化,面元划分详解

pd.cut pandas.cut(x, bins, right=True, labels=None, retbins=False, precision=3, include_low...

Python中使用copy模块实现列表(list)拷贝

引用是指保存的值为对象的地址。在 Python 语言中,一个变量保存的值除了基本类型保存的是值外,其它都是引用,因此对于它们的使用就需要小心一些。下面举个例子: 问题描述:已知一个列表,...

python生成圆形图片的方法

python生成圆形图片的方法

本文实例为大家分享了python生成圆形图片的具体代码,供大家参考,具体内容如下 # -*- coding: utf-8 -*- """ __author__= 'Du' __...