# -*- coding: utf-8 -*- ‘‘‘ Created on 2015-03-19 Mysql 数据库连接类 ‘‘‘ import MySQLdb class DBOperate: dbhandle = None #建立和数据库系统的连接 def connect(self): self.dbhandle = MySQLdb.connect("localhost","username","password","dbname" ) #获取操作游标 def cursor(self): try: return self.dbhandle.cursor() except (AttributeError, MySQLdb.OperationalError): self.connect() return self.dbhandle.cursor() def commit(self): return self.dbhandle.commit() #关闭连接 def close(self): return self.dbhandle.close() #执行单行sql语句 def execute(self,sql): conn = self.dbhandle.cursor() conn.execute(sql) #执行多条数据 def executemany(self,sql, tmp): conn = self.dbhandle.cursor() conn.executemany(sql, tmp) #查询某几行sql def querymany(self,sql,size): conn = self.dbhandle.cursor() conn.execute(sql) rows = conn.fetchmany(size) return rows #查询1行sql def queryone(self,sql): conn = self.dbhandle.cursor() conn.execute(sql) rows = conn.fetchone() return rows #查询所有行sql def queryall(self,sql): conn = self.dbhandle.cursor() conn.execute(sql) rows = conn.fetchall() return rows
原文:http://www.cnblogs.com/fanlianrong/p/4571668.html