Last active
December 13, 2016 03:30
-
-
Save tawateer/b37b4be09131539e019be072a17f4158 to your computer and use it in GitHub Desktop.
Mysql util
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/env python | |
# -*- coding: utf-8 -*- | |
import sys | |
import MySQLdb | |
class MysqlConn(object): | |
def __init__(self, host, port, user, passwd, db=None): | |
if db is None: | |
self.db = MySQLdb.connect(host=host,port=port,user=user,passwd=passwd,connect_timeout=3) | |
else: | |
self.db = MySQLdb.connect(host=host,port=port,user=user,passwd=passwd,db=db,connect_timeout=3) | |
def select(self, sql, close=True): | |
cur = self.db.cursor() | |
cur.execute(sql) | |
# row = cur.fetchone() | |
row = cur.fetchall() | |
cur.close() | |
if close: | |
self.db.close() | |
return row | |
def change(self, sql, close=True): | |
cur = self.db.cursor() | |
try: | |
cur.execute(sql) | |
self.db.commit() | |
return True | |
except Exception, e: | |
self.db.rollback() | |
finally: | |
cur.close() | |
if close: | |
self.db.close() | |
return False | |
def sqls(self, _sqls, close=True): | |
cur = self.db.cursor() | |
try: | |
# cur.execute("set autocommit=0 ") | |
for sql in _sqls: | |
cur.execute(sql) | |
self.db.commit() | |
res = cur.fetchall() | |
return res | |
except Exception, e: | |
self.db.rollback() | |
finally: | |
cur.close() | |
if close: | |
self.db.close() | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment