使用python将json插入mysql

时间:2017-09-21 02:55:36

标签: python mysql sql pymysql

您好我能查询但无法使用下面的代码插入我的json字段,问题不是很难但是由于我对mysql的绝对新手无法弄清楚..每次我都会得到一个变量调用last_time首先我需要插入然后从第二次我需要更新last_time ..如果我手动我能够做到并根据需要获得输出..如下面的照片..

enter image description here

import pymysql.cursors
import datetime
import json

last_time='2344' #this value i will get output from my program

connection = pymysql.connect(host='localhost',
                         user='root',
                         password='Admin...',
                         db='cl......',
                         charset='utf8mb4',
                         cursorclass=pymysql.cursors.DictCursor)
print "connect successfull"

try:
   with connection.cursor() as cursor:
      sql = "INSERT INTO `tt_inv_refresh` (`cust_id`, `res_type`, `refresh_dtls`) VALUES (%s, %s, %s)"
      cursor.execute(sql, ('2','elb','{"vot":[{"elb":"name1","last_refreshtime":last_time},{"elb":"name2","last_refreshtime":last_time}]}'))
connection.commit()

except Exception as e:
   print str(e)

print "inserted"

finally:
   connection.close()
如果有人在我的代码中指出错误,

将有义务...谢谢

1 个答案:

答案 0 :(得分:2)

您错过了last_time

周围的引用

更正cursore.execute

的行
cursor.execute(sql, ('2','elb','{"vot":
      [{"elb":"name1","last_refreshtime":' + last_time + '},
      {"elb":"name2","last_refreshtime":' + last_time+ '}]}'))

为避免将来出现此类问题,您可以考虑定义一个对象并使用json.dumps

class Elb:

    def toJSON(self):
        return json.dumps(self, default=lambda o: o.__dict__, 
        sort_keys=True, indent=4)

    # you can use array or dict | I just copied from one of my code
    # which reqd it to be an array
    def mapper(self, detailArray = []): # you can use array or dict
        self.elb = detailArray[0];
        self.last_refreshtime = detailArray[1];

因此,在为实例设置数据后,请

el_instance = Elb()
el_instance.mapper(<array-with-data>)

您可以致电el_instance.toJSON()在任何地方获取序列化数据。