批量插入数据库数据,有则更新,无则追加

# 批量插入数据库数据,有则更新,无则追加
import pymysql
import numpy as np
import pandas as pd
conn = pymysql.connect(
host='127.0.0.1',
port=3306,
user='root',
passwd='root',
db='py3_userinfo',
charset='utf8'
)
# 游标
cur = conn.cursor()
df = pd.DataFrame([['合肥', 12, 110],['北京', 11, 112],['上海', 11, 113],['上海', 100, 113]],columns=['name', 'age', 'tel'])
train_data = np.array(df) # np.ndarray()
train_x_list=train_data.tolist() # list
sql="insert into student(name,age,tel) values(%s,%s,%s) ON DUPLICATE KEY UPDATE age=age+values (age)"
cur.executemany(sql,train_x_list)
conn.commit()
conn.close()
posted @ 2019-06-21 11:40  chenyibai  阅读(1179)  评论(0编辑  收藏  举报