【问题标题】:How to store python dictionary in to mysql DB through python如何通过python将python字典存储到mysql DB
【发布时间】:2013-10-31 09:48:43
【问题描述】:

我正在尝试通过将字典转换为字符串然后尝试插入来将以下字典存储到 mysql DB 中,但出现以下错误。如何解决这个问题,或者有没有其他方法可以将字典存储到 mysql DB 中?

dic = {'office': {'component_office': ['Word2010SP0', 'PowerPoint2010SP0']}}
d = str(dic)

# Sql query
sql = "INSERT INTO ep_soft(ip_address, soft_data) VALUES ('%s', '%s')" % ("192.xxx.xx.xx", d )

soft_data is a VARCHAR(500)

错误: 执行异常(1064,“您的 SQL 语法有错误;请查看与您的 MySQL 服务器版本相对应的手册以获取正确的语法 在'office'附近使用:{'component_office': ['Word2010SP0', 'PowerPoint2010SP0' at line 1")

有什么建议或帮助吗?

【问题讨论】:

    标签: python mysql dictionary


    【解决方案1】:

    首先,永远不要构建这样的原始 SQL 查询。永远不能。这就是参数化查询的用途。您要求进行SQL injection 攻击。

    如果您想存储任意数据,例如 Python 字典,您应该序列化该数据。 JSON 将是格式的不错选择。

    总体而言,您的代码应如下所示:

    import MySQLdb
    import json
    
    db = MySQLdb.connect(...)    
    cursor = db.cursor() 
    
    dic = {'office': {'component_office': ['Word2010SP0', 'PowerPoint2010SP0']}}
    sql = "INSERT INTO ep_soft(ip_address, soft_data) VALUES (%s, %s)"
    
    cursor.execute(sql, ("192.xxx.xx.xx", json.dumps(dic)))
    cursor.commit()
    

    【讨论】:

    • 如何在服务器另一端反序列化数据?
    • @VignanBandi: dic = json.loads(str_from_db)
    【解决方案2】:

    如下修改你的代码:

    dic = {'office': {'component_office': ['Word2010SP0', 'PowerPoint2010SP0']}}
    d = str(dic)
    
    # Sql query
    sql = """INSERT INTO ep_soft(ip_address, soft_data) VALUES (%r, %r)""" % ("192.xxx.xx.xx", d )   
    

    【讨论】:

    • 它仍然抛出相同的错误(1064,'您的 SQL 语法有错误;请查看与您的 MySQL 服务器版本相对应的手册,以获取在 \'192.xxx 附近使用的正确语法。 x.xxx\'\', \'"{\'component_office\': [\'Word2010SP0\']}"\' 在第 1 行')
    • 好的,把 d = str(dict) 改成 d = json.dumps(dic)。
    • 感谢输入 MySQLdb.escape_string() 解决了问题
    【解决方案3】:

    试试这个:

    dic = { 'office': {'component_office': ['Word2010SP0', 'PowerPoint2010SP0'] } }
    
    "INSERT INTO `db`.`table`(`ip_address`, `soft_data`) VALUES (`{}`, `{}`)".format("192.xxx.xx.xx", str(dic))
    

    dbtable 更改为您需要的值。

    【讨论】:

    • 通过这样做我得到以下异常(1054,“'字段列表'中的未知列'192.xx.xx.xxx'”)
    • INSERT中的d更改为dic
    • 我试过这个脚本,它工作正常你能打印你的代码和回溯吗?很难理解错误在哪里,另一种选择只尝试 mysql work-branch 的 SQL 语句。
    • 感谢输入 MySQLdb.escape_string() 解决了问题
    • 如果有人在 2013 年以外的时间阅读此内容:错误是由于花括号周围的反引号引起的。它们应该是单引号。
    【解决方案4】:

    清理输入是个好主意,当需要在查询中多次使用同一个变量时,“.format”很有用。 (这个例子不是你要的)

    dic = {'office': {'component_office': ['Word2010SP0', 'PowerPoint2010SP0']}}
    ip = '192.xxx.xx.xx'
    with conn.cursor() as cur:
      cur.execute("INSERT INTO `ep_soft`(`ip_address`, `soft_data`) VALUES ({0}, '{1}')".format(cur.escape(ip),json.dumps(event)))
      conn.commit()
    

    如果不使用 cur.escape(variable),则需要将占位符 {} 括在引号中。

    【讨论】:

      【解决方案5】:

      这个答案有一些关于连接对象的伪代码,mysql 的风格是 memsql,但除此之外它应该很容易理解。

      import json
      #... do something
      a_big_dict = getAHugeDict()  #build a huge python dict
      conn = getMeAConnection(...)
      serialized_dict = json.dumps(a_big_dict) #serialize dict to string
      #Something like this to hold the serialization...
      qry_create = """
      CREATE TABLE TABLE_OF_BIG_DICTS (
      ROWID BIGINT NOT NULL AUTO_INCREMENT,
      SERIALIZED_DICT BLOB NOT NULL,
      UPLOAD_DT TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
      KEY (`ROWID`) USING CLUSTERED COLUMNSTORE
      );
      """
      conn.execute(qry_create)
      #Something like this to hold em'
      qry_insert = """
      INSERT INTO TABLE_OF_BIG_DICTS (SERIALIZED_DICT)
      SELECT '{SERIALIZED_DICT}' as SERIALIZED_DICT;
      """
      #Send it to db
      conn.execute(qry_insert.format(SERIALIZED_DICT=serialized_dict))
      #grab the latest
      qry_read = """
      SELECT a.SERIALIZED_DICT
      from TABLE_OF_BIG_DICTS a
      JOIN 
      (
          SELECT MAX(UPLOAD_DT) AS MAX_UPLOAD_DT
          FROM TABLE_OF_BIG_DICTS
      )                           b
      ON  a.UPLOAD_DT = b.MAX_UPLOAD_DT
      LIMIT 1
      """
      
      #something like this to read the latest dict...
      df_dict = conn.sql_to_dataframe(qry_read)
      dict_str = df_dict.iloc[df_dict.index.min()][0]
      
      #dicts never die they just get rebuilt
      dict_better = json.loads(dict_str)
      

      【讨论】:

        猜你喜欢
        • 2011-10-29
        • 1970-01-01
        • 2013-12-09
        • 2018-04-05
        • 1970-01-01
        • 2018-05-10
        • 2021-08-07
        • 2015-11-26
        • 2018-11-23
        相关资源
        最近更新 更多