1.pip安装模块
pip install mysqlclient
2.引入下面的类
import MySQLdb
class MySqlOp(object):
def __init__(self, login_msg):
self.host = login_msg[0]
self.port = login_msg[1]
self.db_name = login_msg[2]
self.user = login_msg[3]
self.passwd = login_msg[4]
self.charset = 'utf8'
def operate(self, sql):
db = MySQLdb.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db_name, charset=self.charset)
cur = db.cursor()
try:
cur.execute(sql)
cur.close()
db.commit()
except Exception as e:
print(e)
cur.close()
db.rollback()
db.close()
def select(self, sql):
db = MySQLdb.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db_name, charset=self.charset)
cur = db.cursor()
results = None
try:
cur.execute(sql)
results = cur.fetchall()
except Exception as e:
print(e)
db.close()
return results
def callproc(self, sql, args=[]):
db = MySQLdb.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db_name, charset=self.charset)
cur = db.cursor()
results = None
try:
cur.callproc(sql, args)
results = cur.fetchall()
cur.close()
db.commit()
except Exception as e:
print(e)
cur.close()
db.rollback()
db.close()
return results
@classmethod
def int_c(cls, int_):
'''
整数处理
'''
return int_ if int_ else 'null'
@classmethod
def str_c(cls, str_):
'''
字符串处理
'''
return "'{}'".format(str_) if str_ else 'null'
3.使用
if __name__ == '__main__':
login_msg = ['192.168.0.1', 3306, 'student_db', 'paisen', 'abcd1234']
msq = MySqlOp(login_msg)
book = msq.select('''show full columns from data;''')
print(book)
msq.operate('''insert into student (no, name) values (1, "刘华强");''')
cover = msq.callproc('getDataCoverPath', [100,])
print(cover)