pymysql中如何將動態的插入數據庫中
阿新 • • 發佈:2018-10-01
class https val form lba clas key () com
data = { ‘id‘: ‘1‘, ‘name‘: ‘zengsf‘, ‘age‘: 20 } table = ‘students‘ #獲取到一個以鍵且為逗號分隔的字符串,返回一個字符串 keys = ‘, ‘.join(data.keys()) values = ‘, ‘.join([‘%s‘] * len(data)) sql = ‘INSERT INTO {table}({keys}) VALUES ({values})‘.format(table=table, keys=keys, values=values) try: #這裏的第二個參數傳入的要是一個元組if cursor.execute(sql, tuple(data.values())): print(‘Successful‘) db.commit() except: print(‘Failed‘) db.rollback() db.close()
參考地址:https://cuiqingcai.com/5578.html
pymysql中如何將動態的插入數據庫中