1. 程式人生 > >Python模組的使用-- pymysql通過字典插入資料

Python模組的使用-- pymysql通過字典插入資料

首先建data庫,data庫裡有users表有name和age兩個欄位

import pymysql 

db =  pymysql.connect(host='127.0.0.1', port=3306, user='root', password='123', db='data') 

cursor = db.cursor()

a = {"name": 'fan123', 'age': '123'}

cols = ", ".join('`{}`'.format(k) for k in a.keys())
print(cols)  # '`name`, `age`'

val_cols =
', '.join('%({})s'.format(k) for k in a.keys()) print(val_cols) # '%(name)s, %(age)s' sql = "insert into users(%s) values(%s)" res_sql = sql % (cols, val_cols) print(res_sql) # 'insert into users(`name`, `age`) values(%(name)s, %(age)s)' cursor.execute(res_sql, a) # 將字典a傳入 db.commit()

批量插入

a =
[{'age': '123', 'name': 'fake'}, {'age': 456, 'name': 'gigi'}, {'age': 23, 'name': 'qq'}] # 拼出要插入的內容 cursor.executemany(res_sql, a) db.commit()