当前位置: 移动技术网 > IT编程>脚本编程>Python > 封装一个数据库模块有三个功能:查询,插入,关闭

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

2019年11月28日  | 移动技术网IT编程  | 我要评论

伦紫玄,千叶真一纹身,杭州九堡客运中心

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

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()

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网