把这乱七八糟的东西换掉#UPDATED with column_names
k=0
for i in jsonobject:
# Connect to the database
conn = pymysql.connect(host='10.20.3.4', port=3306, user='root', passwd='', db='python_db')
try:
with conn.cursor() as cursor:
column_names = ['col1','col2','col3',...'col11']
column_names_str = ', '.join(column_names)
binds_str = ', '.join('%s' for _ in range(len(column_names)))
sql=("INSERT INTO `json_test` ({column_names})" \
" VALUES({binds})"
.format(column_names=column_names_str,binds=binds_str))
for data_dict in jsonobject:
values = [data_dict[column_name]
for column_name in column_names]
cursor.execute(sql, values)
print("Insert successfull!")
#UPDATED
k+=1
conn.commit()
finally:
conn.close()
return "Insert successful"
与
^{pr2}$
总和k对象是冗余的
另外,名称i不清楚,让我觉得它是某种索引,而实际上它不是:它是一个dict对象
我们不需要从jsonobject为每个对象创建连接,因为这是一个昂贵的操作
我们不需要在每次迭代中创建sql对象(它保持不变)
将列名存储在list/tuple中可以避免在查询和值提取中两次写入它们。在
正在创建绑定str%s, %s, ...
当我们错过/添加了太多绑定别名时,根据列数动态地保存我们的打印错误