10-21 5,160 views
适用于python 3+ pymsql 扩展类,包含增删改查
首先要安装pymsql , pip install pymysql
document : https://pypi.org/project/PyMySQL/
github :https://github.com/PyMySQL/PyMySQL
pipy : https://pypi.org/project/PyMySQL/
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pymysql
import time
class MySQL:
error_code = '' #MySQL错误号码
_instance = None #本类的实例
_conn = None # 数据库conn
_cur = None #游标
_TIMEOUT = 30 #默认超时30秒
_timecount = 0
dbconfig = {'host': '',
'port': 3306,
'user': '',
'passwd': '',
'db': '',
'charset': 'utf8'}
def __init__(self):
self._conn = pymysql.connect(host=self.dbconfig['host'],
port=self.dbconfig['port'],
user=self.dbconfig['user'],
passwd=self.dbconfig['passwd'],
db=self.dbconfig['db'],
charset=self.dbconfig['charset'])
self._cur = self._conn.cursor()
self._instance = pymysql
def query(self,sql,str=''):
self._cur.execute("SET NAMES utf8")
if (str != ''):
return self._cur.execute(sql,str)
else:
return self._cur.execute(sql)
def update(self,sql,str=''):
try:
self._cur.execute("SET NAMES utf8")
result = self._cur.execute(sql,str)
self._conn.commit()
except Exception :print("发生异常")
return result
def insert(self,sql,str=''):
self._cur.execute("SET NAMES utf8")
self._cur.execute(sql,str)
self._conn.commit()
return self._cur.lastrowid
def fetchAllRows(self):
return self._cur.fetchall()
def fetchOneRow(self):
return self._cur.fetchone()
def getRowCount(self):
return self._cur.rowcount
def commit(self):
self._conn.commit()
def rollback(self):
self._conn.rollback()
def __del__(self):
try:
self._cur.close()
self._conn.close()
except:
pass
def close(self):
self.__del__()
if __name__ == '__main__':
# 连接数据库,创建这个类的实例
db = MySQL()
db.query("SELECT id FROM table WHERE title=%s" ,('搜索词'))
if (db.getRowCount()):
print('查到了')
else:
print('未查到')
# 操作数据库
insert_id = db.insert("insert into table(title,name) values(%s,%s)",('lalala','pitter'))
print(insert_id)