数据库示例

import pymysql
db = pymysql.connect(host='localhost', user='root', password='pz2212', port=3306, db='spiders')
cursor = db.cursor()
data = {
    'id': '20120001',
    'name': 'Bob',
    'age': 20
}
table='students'
keys=','.join(data.keys())
values=','.join(['%s']*len(data))
##print(keys,values)
sql='insert into {table}({keys}) values({values}) ON DUPLICATE KEY UPDATE'.format(table=table,keys=keys,values=values)
sql_update = 'UPDATE students SET age = %s WHERE name = %s'
try:
    if cursor.execute(sql,tuple(data.values())):
        print('成功插入数据')
        db.commit()
except:
    print('插入数据失败')
    db.rollback()
db.close()

 

posted @ 2019-03-13 16:42  晨光曦微  阅读(223)  评论(0编辑  收藏  举报