链接和关闭链接mysql类
#!/usr/bin/env python3
#-*- encoding:utf-8 -*-
import pymysql
#mysql 连接类
class mysqlCommand():
def __init__(self,host,port,user,passwd,db):
self.conn = pymysql.connect(host = host , port = port , user = user , passwd = passwd , db = db)
def connects(self):
return self.conn
#关闭mysql连接
def close(self):
self.conn.close()
增、删、改、查类(只完成部分,后面会完善)
#!/usr/bin/env python3
#-*- coding:utf-8-*-
#mysql 映射类
class mapper_abstract():
def __init__(self,object):
self.conn = object
def cur(self):
cur = self.conn.cursor()
return cur
#查找
def findAll(self,table):
try:
cur = self.cur()
cur.execute("SELECT * FROM %s"%(table))
result = cur.fetchall()
return result
except:
print ('mysql error')
#删除
def dels(self,table,ids):
sql="delete from `%s` where id='%d'" % (table,ids)
try:
cur = self.cur()
cur.execute(sql)
self.conn.commit()
except:
self.conn.rollback()
类的实例化调用示例
#!/usr/bin/env python3
#-*- coding:utf-8-*-
from mysql import mysqlCommand
from mapper import mapper_abstract
db = mysqlCommand('127.0.0.1',3306 ,'root' ,'pwd' ,'table')
conn = db.connects()
mapper = mapper_abstract(conn)
result = mapper.findAll('blog_categray')
for each in result:
print (each)