【问题标题】:HINT: There is a column named "title" in table "wenzhang", but it cannot be referenced from this part of the query提示:“wenzhang”表中有一个名为“title”的列,但不能从这部分查询中引用
【发布时间】:2019-11-04 03:12:32
【问题描述】:

我正在尝试从 spyder 插入内容。我成功连接到数据库。然后错误发生了。

connet = psycopg2.connect(database="sample", 
user="users",password="123456",host="localhost",port="5432")

cursor = connet.cursor()

def downloadPage(url):
    content=''
    response = requests.get(url)
    response.encoding = 'UTF-8'
    bs = BeautifulSoup(response.text,'lxml')
    title = bs.find('h1').text
    div = bs.find('div',attrs={'class':'neirong'})
    ps = div.findAll('p')

    for p in ps:
        content+=p.text+'\n'
    return title,content

for url in urls:
    title,content = downloadPage(url)
    print(title)
    sql = "insert into wenzhang(title,conten) values(title,content)";
    cursor.execute(sql)

错误:

psycopg2.errors.UndefinedColumn: column "title" does not exist
LINE 1: insert into wenzhang(title,conten) values(title,content)
                                                  ^

提示:“wenzhang”表中有一个名为“title”的列,但不能从这部分查询中引用。

【问题讨论】:

  • 您能详细说明您要插入的值吗?它们在哪里定义?
  • sql = "插入文章(title,conten) 值(%s,%s)".format(title,conten).使用这种方式将变量插入查询中,我觉得错误是因为值而不是因为列名。
  • @Murali 不要那样做。这是 SQL 注入的秘诀。
  • @melpomene 是的,对不起,我的错,他可以通过它来执行你所说的功能

标签: python postgresql


【解决方案1】:

目前,您的 value 子句只有 titlecontent 作为裸词,Postgres 将其解释为列名,解释您遇到的错误。

您需要做的是使用execute 方法的第二个参数绑定您拥有的titlecontent 变量:

sql = "insert into wenzhang (title, conten) values (%s, %s)";
cursor.execute(sql, (title, content))

【讨论】:

    【解决方案2】:

    问题是数据库对您的 Python 程序及其变量一无所知。你告诉它运行代码

    insert into wenzhang(title,conten) values(title,content)
    

    所以它认为titlecontent 都是某个表的列。

    pass variables to SQL queries,你可以这样做:

    cursor.execute("insert into wenzhang(title,conten) values(%s, %s)", (title,content))
    

    即使用%s 在您想要在 SQL 查询中插入 Python 值的位置,并将 Python 值列表作为第二个参数传递。

    【讨论】:

      猜你喜欢
      • 2016-06-19
      • 2014-08-08
      • 2018-11-17
      • 2015-07-13
      • 2019-01-14
      • 2021-12-25
      • 1970-01-01
      • 2019-01-06
      • 1970-01-01
      相关资源
      最近更新 更多