简体   繁体   English

如何使用python将这些数据插入到postgresql中?

[英]How do I insert this data into postgresql with python?

In the following codes,I want insert authors by locating link . 在以下代码中,我想通过定位link插入authors

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

And two problems are encountered: 并且遇到两个问题:

  1. Some names are not regular like this: 有些名称不是这样的常规名称:

     LINE 1: UPDATE articles SET authors = Francesco D'Angelo, Roberto T... 
  2. When author names are no problem: 如果作者姓名没有问题:

     """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... 

Don't format your strings with % when you are using SQL, let the driver do the proper escaping: 使用SQL时不要使用%格式化字符串,让驱动程序进行适当的转义:

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

Notice I passed the data as the second argument, execute will take care of escaping the data properly. 注意,我将数据作为第二个参数传递, execute将负责正确地转义数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM