[英]Getting 'TypeError: not all arguments converted during string formatting' in Python PostgreSQL code (other answers not fixing it)
I have read many answers to this same question, but haven't seen anything that works for me.我已经阅读了同一个问题的许多答案,但没有看到任何对我有用的东西。
I have a very basic app just to test things (in app.py and database.py).我有一个非常基本的应用程序只是为了测试东西(在 app.py 和 database.py 中)。 I'm using ElephantSQL, psycopg2-binary and have checked - the table on ElephantSQL is made from this code, but cannot insert from here.
我正在使用 ElephantSQL,psycopg2-binary 并检查过 - ElephantSQL 上的表是由这段代码制成的,但不能从这里插入。 I can obviously insert from ElephantSQL.
我显然可以从 ElephantSQL 插入。
I am just testing with the headline string, but headline will ultimately be the result of a web scrape using bs4.我只是在测试标题字符串,但标题最终将是使用 bs4 进行网络抓取的结果。
This is my first time using a database with Python, but I'm absolutely blocked on what should be quite simple code.这是我第一次在 Python 中使用数据库,但我完全不知道应该是什么非常简单的代码。 Please help.
请帮忙。
This is database.py:这是数据库.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()
this is the main part of my app.py (I've hidden sensitive stuff):这是我的 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)
Returns this error:返回此错误:
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
An INSERT
needs around the values parenthesis, that is also true for placejholders INSERT
需要围绕值括号,对于占位符也是如此
INSERT_HEADLINE = "INSERT INTO headlines (headline) VALUES (%s);
And You need also two elents in a list when you insert, if you have only 1 you need to add and empty one插入时,列表中还需要两个元素,如果只有 1 个,则需要添加并清空一个
cursor.execute(INSERT_HEADLINE, (headline,))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.