将数据库封装成类,单独保存为一个文件,文件名为mysql_template.py
import pymysql
class SqlHelper():
def __init__(self,host,port,db,user,password):
self.host=host
self.port=port
self.db=db
self.user=user
self.password=password
self.charset="utf8"
self.__connect()
# 创建连接和得到游标
def __connect(self):
self.conn=pymysql.connect(host=self.host,port=self.port,db=self.db,
user=self.user,password=self.password,charset=self.charset)
self.cursor=self.conn.cursor()
# 查询一条记录
def fetchone(self,sql,*params):
try:
self.cursor.execute(sql,*params)
# 获取返回的结果(查询有返回结果,增删改没有返回结果)
data=self.cursor.fetchone()
return data
except Exception as e:
print("错误信息是====》",e)
finally:
self.close()
# 查询所有信息
def fetchall(self,sql,*params):
try:
self.cursor.execute(sql,*params)
data =self.cursor.fetchall()
return data
except Exception as e:
print("错误信息是===》",e)
finally:
self.close()
# 增删改的操作
def update1(self,sql,*params):
try:
count=self.cursor.execute(sql,*params)
self.conn.commit()
return count
except Exception as e:
print("错误信息为===》",e)
# rollback回滚的意思。 就是数据库里做修改后 ( update, insert, delete)未commit
# 之前使用rollback可以恢复数据到修改之前。
self.conn.rollback()
finally:self.close()
# 关闭资源方法
def close(self):
if self.cursor !=None:
self.cursor.close()
if self.conn !=None:
self.conn.close()
之后,随时可以调用函数来使用mysql了。例如下面代码,里面有点乱,但知道如何使用就好:
# 引入函数
from mysql_template import SqlHelper
# 创建对象
per=SqlHelper("localhost",3306,"stocks","root","123456")
# 创建表,没有返回结果,如果表已经存在,会报错
# res = per.cursor.execute('create table stock_' + 'mmm' + ' (date varchar(32),open varchar(32),close varchar(32),high varchar(32),low varchar(32),volume varchar(32),p_change varchar(32),unique(date))')
# print(res)
# 如果数据表已经存在使用 execute() 方法删除表。
per.cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
# 创建数据表SQL语句
sql = """CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )"""
per.cursor.execute(sql)
# 获取一条信息
data=per.fetchone("select * from stock_002930")
print(data)
# 获取所有的对象
data1=per.fetchall("select *from emp")
print(data1)
#增加用户
one="insert into allstock VALUE (%s,%s,%s,%s)"
one1=["难兄","男","9999","2"]
count=per.update1(one,one1)
print(count)
#删除用户
two="delete from emp where deptid=%s"
two1=(3)
count=per.update1(two,two1)
print(count)
#查询总数量
sql = "select count(*) from emp "
data = per.fetchall(sql)
print(data)
#将数据库的记录输出
class User(object):
def __init__(self,id,name,age,sex,tel,deptid):
self.id = id
self.name = name
self.age = age
self.sex = sex
self.tel = tel
self.deptid = deptid
def __str__(self):
return "用户名称%s,用户电话%s,用户性别%s,用户年龄%s" %(self.name,self.tel,
self.sex,self.age)
data2=per.fetchall("select *from emp")
print(data2)
list=[]
for x in data2:
u=User(x[0],x[1],x[2],x[3],x[4],x[5])
list.append(u)
for i in list:
print(i)