如何将字典值保存到mysql数据库中?

lmvvr0a8  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(785)

我想将dictionary中存储的值从tkintergui保存到mysql数据库中,值的dictionary如下所示。目前我使用if-else语句来表示每一个非常长的长度。

db=storage.connect()
cursor=db.cursor()
sd1={'AWB Fees': ('122', 'Rupees', '1', '34', '4', '136.00', '8', '10.88'), 
    'Agency Charges': ('122', 'Rupees', '1', '78', '4', '312.00', '8', 
    '24.96'),'AWB': ('122', 'Rupees', '1', '34', '4', '136.00', '8', 
    '10.88')}
length=len(sd1)

y = (sd1.keys())

if (length==1):
    za = ((tuple(y))[0])
    xa = ((sd1[za])[0])
    xb = ((sd1[za])[1])
    xc = ((sd1[za])[2])
    xd = ((sd1[za])[3])
    xf = ((sd1[za])[4])
    xg = ((sd1[za])[5])
    xh = ((sd1[za])[6])
    xi = ((sd1[za])[7])
    cursor.execute(
            "INSERT INTO sea_exp_tra_raiselocal_inv_fright_est 
            (rlcn_id,billing_head, sac, currency, ex_rate, rate, value, 
            amount, gst, gst_amnt) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",
            (sepmId,za,xa,xb,xc,xd,xf,xg,xh,xi))
else:
    pass
db.commit()
db.close()
uz75evzq

uz75evzq1#

你真的把事情搞得太复杂了。首先让我们清理代码:

sd1 = {
  'AWB Fees': ('122', 'Rupees', '1', '34', '4', '136.00', '8', '10.88'), 
  'Agency Charges': ('122', 'Rupees', '1', '78', '4', '312.00', '8', '24.96'),
  'AWB': ('122', 'Rupees', '1', '34', '4', '136.00', '8', '10.88')
  }

sql = """
  INSERT INTO sea_exp_tra_raiselocal_inv_fright_est 
  (rlcn_id,billing_head, sac, currency, ex_rate, rate, value, amount, gst, gst_amnt) 
  VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
"""

key = list(d.keys())[0]    
values = (sepmId, key,) + sd1[key]
cursor.execute(sql, values)

现在你要做的就是迭代 sd1.items() (生成键、值对):

sd1 = {
  'AWB Fees': ('122', 'Rupees', '1', '34', '4', '136.00', '8', '10.88'), 
  'Agency Charges': ('122', 'Rupees', '1', '78', '4', '312.00', '8', '24.96'),
  'AWB': ('122', 'Rupees', '1', '34', '4', '136.00', '8', '10.88')
  }

sql = """
  INSERT INTO sea_exp_tra_raiselocal_inv_fright_est 
  (rlcn_id,billing_head, sac, currency, ex_rate, rate, value, amount, gst, gst_amnt) 
  VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
"""

for key, val in sd1.items():    
    values = (sepmId, key,) + val
    cursor.execute(sql, values)

相关问题