美文网首页
2020-11-17python封装写入mysql方法 一条龙全

2020-11-17python封装写入mysql方法 一条龙全

作者: 217760757146 | 来源:发表于2020-11-18 20:16 被阅读0次

    mysql在数据保存中用的还是比较多的 但是书写比较繁琐 考虑做一个封装

    操作mysql步骤 1.连接数据库 2.获取游标 3.通过游标执行sql语句 4.关闭开启的
    做了一个简单的封装

    import pymysql
    #连接数据库
    def dbHandle():
        conn = pymysql.connect(
            host="127.0.0.1",
            port=3306,
            user="xxxx",
            password="xxxxxx",
            db="xxxxxxxx",
            charset="utf8",
        )
        return conn
    def createtable(alist):
        # alist = ['a','s','g','b','t']
        alis = ' CHAR(250),'.join(alist)+' CHAR(250)'
        print(alis)
        coon = dbHandle()#建立连接
        cur = coon.cursor()#获取游标
        table = "create table test1(id INT,{})".format(alis)#mysql新建表格的语句
        table = "create table test1({})".format(alis)#mysql新建表格的语句
    
        cur.execute(table)#执行语句
    # 打开表 写入表 关闭表
    
    def writeMYSQL(tablename, listkey,listvalue):
    
        dbObject = dbHandle()
        cursor = dbObject.cursor()
        #tablename='xxxxxx'
        # listkey = ['a','s','g','b','t']
        # listvalue= ['a','s','g','b','t']
        listkey = ','.join(listkey)
        listvalue = '"'+'","'.join(listvalue)+'"'
        print(listkey,listvalue)
    
        sql = """INSERT INTO {}({})
             VALUES ({})""".format(tablename,listkey,listvalue)
        print(sql)
        try:
            # 执行sql语句
            cursor.execute(sql)
            # 提交到数据库执行
            dbObject.commit()
            print('写入成功')
        except Exception as e:
            print(e)
            # Rollback in case there is any error
            dbObject.rollback()
            # 关闭数据库连接
            dbObject.close()
    

    实现功能

    1.建表 输入一个键列表 在指定数据库中新建一个表格 为减少输入默认字符串长度250
    2.插入字符串 给出一个借口 通过输入键值两个list及表名即可插入
    这个插入方法比较低效 还有一种to_sql的方法 后续可以改进(https://blog.csdn.net/m0_38126296/article/details/93386904

    相关文章

      网友评论

          本文标题:2020-11-17python封装写入mysql方法 一条龙全

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