2.python封装mysql插入数据,可以插入多条——python学习笔记

目录结构
在这里插入图片描述
pip安装pymysql

import pymysql
import pymysql.cursors
import json
import hashlib


def connectdb():
    print('连接到mysql服务器...')
    # 打开数据库
    db = pymysql.connect("localhost", "root", "root", "test")
    print('连接上了!')
    return db


def closedb(db):
    db.close()
    print('链接关闭了')


def find(db, sql):
    cursor = db.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        # 执行sql语句
        cursor.execute(sql)
        results = cursor.fetchall()
        print(json.dumps(results))
        return results

    except:
        # Rollback in case there is any error
        print('查询数据失败!')
        return 'None'


def insertUser(db, table, arr):
    index = 0
    insertVal = []
    insertKeString = ''
    cursor = db.cursor()
    while index < len(arr):
        item = 0
        for key in arr[index]:
            insertVal.append(str(arr[index][key]).replace("\n", ""))
            if item == len(arr[index]) - 1:
                insertKeString += '`' + str(key) + '`'
                insertVal = tuple(insertVal)
                string = '(' + insertKeString + ')'
                sqlStr = "INSERT INTO `py_key` " + string + " VALUES " + str(
                    insertVal) + ';'
                print(sqlStr)
                cursor.execute(sqlStr)
                # 提交到数据库执行
                db.commit()
                print("遍历完成")
            else:
                insertKeString += '`' + str(key) + '`' + ', '
                print('仍在遍历中' + str(len(arr[index])))
                print(item)
            item += 1
        index += 1


使用
在这里插入图片描述
先引入
我这里是保存rsa密匙对

def insertUser(db, table, arr):

db是mysql链接,table是表名,arr是列表嵌套字典,这样就可以像php一样用数组嵌套数组来实现多条插入数据库

con = db.connectdb()
db.insertUser(con, 'py_key', [{'public_pen': PUBLIC_PEM.decode('utf-8'), 'private_pen': PRIVATE_PEM.decode('utf-8'),
                                   'create_time': time.time(), 'ip': ip}])

最后,如果有什么不对的地方,望大侠们指出!

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值