利用python和MySQL数据库实现基本的数据插入

import pymysql
try:
    db = pymysql.connect(host='localhost', user='root', password='112223', port=3306, db='test')
    cursor = db.cursor()
    data = {
        'test_id': '"5555"',
        'test_name': '"Lilei"'

    }
    table = 'test_detail'
    keys = ', '.join(data.keys())
    values = ', '.join(data.values())
    #print(values)
    sql = 'INSERT INTO {}({}) VALUES ({})'.format(table,keys,values)
    cursor.execute(sql)
    db.commit()
    cursor.close()
    db.close()
except :
    print('插入失败')

其中test为数据库的名称

test_detail为数据库表的名称

test_id与test_name为数据库表中的列名

可根据自己的需要修改

利用python和MySQL数据库实现基本的数据插入