美文网首页
python3使用pymysql连接数据库,实现CRUD

python3使用pymysql连接数据库,实现CRUD

作者: Luy_ | 来源:发表于2020-09-27 15:59 被阅读0次

一.官方文档

二.CRUD方法整合

'''
@author: Luy
@data:2020-09-27 13:15
@Summary:使用pymysql,实现增删改查
'''

import pymysql


class DB():
    def __init__(self, host='db_host', port=3306, db='ab_table', user='userName', passwd='passwd', charset='utf8'):
        # 建立连接 
        self.conn = pymysql.connect(host=host, port=port, db=db, user=user, passwd=passwd, charset=charset)
        # 创建游标,操作设置为字典类型        
        self.cur = self.conn.cursor(cursor=pymysql.cursors.DictCursor)

    def __enter__(self):
        # 返回游标        
        return self.cur

    def __exit__(self, exc_type, exc_val, exc_tb):
        # 提交数据库并执行        
        self.conn.commit()
        # 关闭游标        
        self.cur.close()
        # 关闭数据库连接        
        self.conn.close()

#传入sql执行
def executeSql(sql = ''):
    with DB() as db:
        db.execute(sql)
        print(db)
        for i in db:
            print(i)

if __name__ == '__main__':
    #sql语句
    sql = """SELECT * FROM `***`.`***` WHERE `id` = '***' LIMIT **"""
    executeSql(sql)

相关文章

网友评论

      本文标题:python3使用pymysql连接数据库,实现CRUD

      本文链接:https://www.haomeiwen.com/subject/lihluktx.html