Python mysqldb模块
2013-09-24 20:47
375 查看
#!/usr/bin/env python2.7 #-*- coding:utf8 -*- import os import sys import logging import MySQLdb from log import Logger logger=Logger("../log/",logging.DEBUG,"mysql_base.log") class MySQLBase(object): """MySQLBase""" def __init__(self,host,port,user,passwd,db='',charset='utf8',connect_timeout=1,retry_time=3,use_unicode=1): self.__host = host self.__port = port self.__user = user self.__passwd = passwd self.__db = db self.__charset = charset self.__connect_timeout = connect_timeout self.__retry_time = retry_time self.__use_unicode = use_unicode self.__connection = self._connection() def _connection(self): connection = None for i in xrange(0,self.__retry_time): try: connection = MySQLdb.connect(host=self.__host,port=int(self.__port),user=self.__user,passwd=self.__passwd,db=self.__db,connect_timeout=self.__connect_timeout,charset=self.__charset,use_unicode=self.__use_unicode) break except Exception,e: if i == self.__retry_time - 1: message = "Failed to connect to host=%s,port=%s,Error_No:%d,\"%s\"" % (self.__host,self.__port,e[0],str(e[1])) logger.error(message) print message #os._exit(1) exit(1) continue return connection def cursor(self): connection = self.__connection cursor = connection.cursor(cursorclass=MySQLdb.cursors.DictCursor) cursor.execute("set interactive_timeout=28800;") cursor.execute("set wait_timeout=288000;") return cursor def close(self): connection = self.__connection if connection: connection.close() def main(): host = "127.0.0.1" port = "5580" user = "pt" passwd="123456" mysql_base = MySQLBase(host=host,port=port,user=user,passwd=passwd) cursor = mysql_base.cursor() sql = "show databases" cursor.execute(sql) result = cursor.fetchall() for row in result: print row mysql_base.close() if __name__ == "__main__": main()
上述代码对于mysqldb简单封装了一下,更多使用介绍参照
http://zetcode.com/db/mysqlpython/
http://mysql-python.sourceforge.net/MySQLdb.html
相关文章推荐
- Python安装MySQLdb模块(Linux)
- python 安装MySQLdb模块
- windows下python 安装mysqldb模块
- Python MySQLdb模块连接操作mysql数据库实例
- Python 的 MySQLdb 模块插入数据没有成功与 autocommit(自动提交)的关系
- python mysql 简单总结(MySQLdb模块 需另外下载)
- Python爬虫学习笔记--MySQLdb模块
- Windows 10 64位下安装python2模块MySQLdb(MySQL-python)遇到的坑
- easy_install安装python的MySQLdb模块
- centos7安装python的MySQLdb模块
- Python学习之MySQLdb模块
- centos7 使用pip安装python-mysqldb模块出现的问题:
- python安装MySQLDb模块
- Python的MySQLdb模块安装(转:一个人的旅行)
- Python的MySQLdb模块安装,连接,操作,增删改
- python模块整理18-MySQLdb
- Python MySQLdb模块的安装与使用
- python辅助开发模块(非官方)如pil,mysqldb,openpyxl,xlrd,xlwd
- python2.7 MySQLdb模块在win32下安装