我已经读了很多关于这个问题的答案,但还没有看到任何适合我的。
我有一个非常基本的应用程序只是测试的东西(在app.py和database.py)。我使用的是ElephantSQL、psycopg2-binary,并且检查过了——ElephantSQL上的表是由这段代码创建的,但不能从这里插入。显然,我可以从ElephantSQL中插入。
我只是在测试标题字符串,但标题最终将是使用bs4 web抓取的结果。
这是我第一次用Python使用数据库,但是我完全被应该非常简单的代码所阻塞。请帮助。
这是database.py:
from psycopg2.extras import execute_values
CREATE_HEADLINES = """CREATE TABLE IF NOT EXISTS headlines
(headline TEXT);"""
INSERT_HEADLINE = "INSERT INTO headlines (headline) VALUES %s;"
SELECT_ALL_HEADLINES = "SELECT * FROM headlines;"
def create_tables(connection):
with connection:
with connection.cursor() as cursor:
cursor.execute(CREATE_HEADLINES)
def create_headlines(connection):
with connection:
with connection.cursor() as cursor:
cursor.execute(CREATE_HEADLINES)
def add_headline(connection, headline):
with connection:
with connection.cursor() as cursor:
cursor.execute(INSERT_HEADLINE, (headline))
def get_headlines(connection):
with connection:
with connection.cursor() as cursor:
cursor.execute(SELECT_ALL_HEADLINES)
return cursor.fetchall()
这是我的app.py的主要部分(我隐藏了敏感的东西):
import psycopg2
from bs4 import BeautifulSoup
import database
connection = psycopg2.connect(db_url)
headline = 'Hello, world!'
print(headline)
print(type(headline))
database.create_tables(connection)
database.create_headlines(connection)
database.add_headline(connection, headline)
返回这个错误:
Hello, world!
<class 'str'>
Traceback (most recent call last):
File "/Users/jamesdanielmalvern/femicide/scraper/app.py", line 33, in <module>
database.add_headline(connection, headline)
File "/Users/jamesdanielmalvern/femicide/scraper/database.py", line 21, in add_headline
cursor.execute(INSERT_HEADLINE, (headline))
TypeError: not all arguments converted during string formatting
INSERT
需要在值括号周围,对于占位符也是如此
INSERT_HEADLINE = "INSERT INTO headlines (headline) VALUES (%s);
当你插入列表时,你也需要两个元素,如果你只有一个元素,你需要添加和清空一个
cursor.execute(INSERT_HEADLINE, (headline,))