【问题标题】:How do I insert this data into postgresql with python?如何使用 python 将这些数据插入到 postgresql 中?
【发布时间】:2016-11-10 03:03:29
【问题描述】:

在下面的代码中,我想通过定位link插入authors

self.cur.execute("""
    UPDATE articles 
    SET authors = %s 
    WHERE link = %s returning id;
""" % (authors, link))
ret_id = self.cur.fetchone()

并且遇到了两个问题:

  1. 有些名字不规则,像这样:

    LINE 1: UPDATE articles SET authors = Francesco D'Angelo,  Roberto T...
    
  2. 当作者姓名没问题时:

    """UPDATE articles SET authors = %s WHERE link = %s returning id;""" % (authors, link))
    psycopg2.ProgrammingError: syntax error at or near ":"
    LINE 1: ...DATE articles SET authors = test WHERE link = http://www.wor...
    

【问题讨论】:

    标签: python postgresql parameter-passing sql-injection psycopg2


    【解决方案1】:

    在使用 SQL 时不要使用% 格式化字符串,让驱动程序进行适当的转义:

    self.cur.execute(
        """UPDATE articles SET authors = %s WHERE link = %s returning id;""", (authors, link))
    

    请注意,我将数据作为第二个参数传递,execute 将负责正确转义数据。

    【讨论】:

      猜你喜欢
      • 2019-02-22
      • 2011-05-13
      • 2018-11-02
      • 1970-01-01
      • 2021-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-06
      相关资源
      最近更新 更多