代码之家  ›  专栏  ›  技术社区  ›  Ynjxsjmh

如何在python MySQLDB VALUE子句中插入字符串列表

  •  0
  • Ynjxsjmh  · 技术社区  · 4 年前

    imploding a list for use in a python MySQLDB IN clause python list in sql query as parameter ,但它们的列表元素都是整数。

    param = []
    param.append(post.title)
    param.append(post.count_vote)
    param.append(post.last_reply_time)
    param.append(post.last_replyer_id)
    param.append(post.poster_id)
    param.append(post.content)
    param.append(post.plain_content)
    param.append(post.relate_unit)
    
    query = "INSERT INTO post (title, countVote, lastReplyTime, lastReplyerId, posterId, content, plainContent, relateUnit) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}');".format(*param)
    
    cursor.execute(query)
    

    元素有很多类型,比如int、str和None。令我困惑的是字符串类型,字符串可能包含 ' " ' 具有 " 以前。但是,我意外地看到一些C代码片段 char ch = 'a'; '

    我想知道有没有办法不经修改就插入字符串?我想到了替换 ' \' ,这是个好主意吗?

    我也试着替换 {0} 等等 ?

    query = "INSERT INTO post (title, countVote, lastReplyTime, lastReplyerId, posterId, content, plainContent, relateUnit) VALUES (?, ?, ?, ?, ?, ?, ?, ?);"
    
    cursor.execute(query, tuple(param))
    # cursor.execute(query, [param,])
    

    都给我错误

    _mysql_exceptions.ProgrammingError: not all arguments converted during string formatting
    
    0 回复  |  直到 4 年前
        1
  •  0
  •   yvesonline    4 年前

    根据你使用的信息 MySQLdb .

    • 尝试使用 format 对于 parameter marker formatting %s , %d
    • 一定要逃走 % ,见文件: Note that any literal percent signs in the query string passed to execute() must be escaped, i.e. %%. 在适用的地方做这个,我做了一个例子 post.content post.plain_content .
    query = "INSERT INTO post (title, countVote, lastReplyTime, lastReplyerId, posterId, content, plainContent, relateUnit) VALUES (%s, %s, %s, %s, %s, %s, %s, %s);"
    cursor.execute(query,post.title, post.count_vote, post.last_reply_time, post.last_replyer_id, post.poster_id, post.content.replace("%", "%%"), post.plain_content.replace("%", "%%"), post.relate_unit)