python - HINT : There is a column named "title" in table "wenzhang", 但不能从这部分查询中引用

标签 python postgresql

我正在尝试插入来自 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”的列,但不能从这部分查询中引用它。

最佳答案

问题在于数据库对您的 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))

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

关于python - HINT : There is a column named "title" in table "wenzhang", 但不能从这部分查询中引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56700538/

相关文章:

python - 来自 Transformers 的 BertForSequenceClassification 的大小不匹配和多类问题

java - SQL 或 Spring JDBC 返回对象的对象

postgresql - 有条件地覆盖单个插入中的默认 PK 序列

python - 使用正则表达式获取忽略字符串的子字符串

python - 在Python中如何确定一个点是否在某个平行四边形内部?

python - 分组时应用自定义函数返回 NaN

python - 斜杠命令不适用于带有 discord bot 的 openai

sql - 在不复制的情况下将表连接到自身

postgresql - Firebase:如何从外部数据库读取?

postgresql - 如何通过更新操作本身维护来自触发器 "before update"的 postgreSQL 锁