第一个包:
第二个包:
第三个包:
# #对脚本进行封装
import MySQLdb
from pymysql0000.read_config import conf
class Db_Utils:
def __init__(self,host,user,passwd,db,port,):
self.host = host
self.user = user
self.passwd = passwd
self.db =db
self.port = port
def get_connection(self):
'''创建数据库的连接对象'''
db = MySQLdb.connect(self.host,self.user,self.passwd,self.db,self.port)
return db
def find_one(self,sql):
'''封装查询一条数据的实例方法'''
db = self.get_connection() #拿到数据库连接对象
cursor = db.cursor() #创建游标对象
cursor.execute(sql)
one = cursor.fetchone() #拿到第一行的数据
return one
def find_all(self,sql):
'''封装查询所有数据的实例方法'''
db = self.get_connection() # 拿到数据库连接对象
cursor = db.cursor() # 创建游标对象
cursor.execute(sql)
all = cursor.fetchall() # 拿到第一行的数据
return all
if __name__ == '__main__':
d = Db_Utils(
host=conf.get_ini_data('db','host'),
user=conf.get_ini_data('db','user'),
passwd=conf.get_ini_data('db','passwd'),
db = conf.get_ini_data('db','db'),
port = int(conf.get_ini_data('db','port')))
print (d.find_one('select * from dept;',))
print (d.find_all('select * from dept;'))