python连接数据库
# -*- 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
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。