python向mysql插入数据

import pymysql
db = pymysql.connect(host=‘47.98.226.11‘,user=‘root‘,password=‘123456‘,port=3306,db=‘jforum‘)
cursor = db.cursor()
data={
‘username‘:‘hui4‘,
‘user_password‘:‘b1d196bdd4580d4ca16af5fdbf746fa251efced39bb9aff25618d0bf9f968a47237bcd4d6863ed0ad9d1b3069d721f139dce72de8c7b078c85ab37ab66cf3876‘,

}
table=‘jforum_users‘
keys=‘,‘.join(data.keys())
values=‘,‘.join([‘%s‘]*len(data))
sql=‘INSERT INTO {table}({keys}) VALUES ({values})‘.format(table=table,keys=keys,values=values)
try:
cursor.execute(sql,tuple(data.values()))
print("Successful")
db.commit()
except:
print("Failed")
db.rollback()
cursor.close()
db.close()

 

相关文章