Python操作Mysql的简单类
#!/usr/bin/env python
#coding=UTF-8
#MYSQL数据操作类
#Author:www.phpdesigner.org Time:2010.7.21 Application-Language:Python2.x
import MySQLdb
import os,sys
class Mysql:
conn = '' #数据库连接对象
cursor = '' #游标
'''
构造函数---对数据库的连接--字符集编码设置
'''
def __init__(self,host = 'localhost',user = 'root',
password = '123456',dbName = 'test',charset = 'utf8'):
try:
self.conn = MySQLdb.connect(host,user,password,dbName)
except Exception,e:
print e
sys.exit()
self.cursor = self.conn.cursor()
self.query('SET NAMES %s' % charset)
'''
SQL执行方法
'''
def query(self,sql):
return self.cursor.execute(sql)
'''
数据查询方法
'''
def show(self):
return self.cursor.fetchall()
'''
析构函数
'''
def __del__(self):
self.cursor.close()
self.conn.close()
if __name__ == '__main__':
mysql = Mysql()
mysql.query('SELECT * FROM user')
data = mysql.show()
for x in data:
print x[1]