由于Python3用PyMySQL取代MySQLdb, 为了兼容, 我们开发的运维管理平台也使用PySQL模块操作数据。
#coding: utf8 import pymysql.cursors class MySQLD_CONN(object): # Connect to the database def get_mysql_connection(self, host='localhost', user='planx', passwd='planx', port=3306): conn=None try: conn = pymysql.connect(host, user, passwd, port=port, charset='utf8', cursorclass=pymysql.cursors.DictCursor) except Exception, e: print(e) return conn def change_table_data(self, conn, db_name, sql): # execute insert, update, delete SQL _status = "OK" if not conn: print("lost database connection!") return None try: with conn.cursor() as cursor: conn.select_db(db_name) cursor.execute(sql) conn.commit() except Exception,e: print(e) _status = "ERROR" finally: cursor.close() return _status def get_table_data(self, conn, db_name, sql): result=None if not conn: print("lost database connection") return result try: with conn.cursor() as cursor: conn.select_db(db_name) cursor.execute(sql) conn.commit() result = cursor.fetchall() except Exception,e: print(e) finally: cursor.close() return result mysql_conn=MySQL_CONN()