封装一个数据库模块有三个功能:查询,插入,关闭

封装一个数据库模块有三个功能:查询,插入,关闭

1.查看

2.提交

3.关闭
import pymysql
cur = None
conn = None

def getall(sql): #用来执行查询
    # 连接数据库
    conn = pymysql.connect(host='localhost', user='root', password='123', db='day300', charset='utf8')
    cur = conn.cursor()          #获取cursor对象
    # 通过cursor的对象去执行SQL语句
    cur.execute(sql)
    return cur.fetchall()

def exceDML(sql): #用来执行插入
    conn = pymysql.connect(host='localhost', user='root', password='123', db='day300', charset='utf8')
    cur = conn.cursor()
# 通过cursor的对象去执行SQL语句
    cur.execute(sql)
    # 提交事物
    conn.commit()

def close():  #用来关闭连接
    if cur:
        cur.close()
    if conn:
        conn.close()


# 使用工具模块:
#
# from day3 import mysqlHelper
#
# name = input("请输入名字:")
# id = input("请输入ID:")
# sql1 = 'insert into t_user values(%d,"%s")'%(int(id),name)
# sql2 = 'select * from t_user'
# mysqlHelper.exceDML(sql1)
# print(mysqlHelper.getall(sql2))
# mysqlHelper.close()

posted @ 2019-11-27 21:59  谢国宏  阅读(441)  评论(0编辑  收藏  举报