我正在尝试插入来自 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)
所以它认为 title
和 content
都是某个表的列。
收件人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/