涉及API、数据库和可视化软件包的项目



首先,这是我在StackOverflow上的第一篇文章,如果我的文章结构不正确,请告诉我。基本上,我是Python的新手,但我一直在尝试将API连接到Python,从Python连接到在线托管的数据库,最后连接到可视化包中。在将Python中的API数据(SheffieldSolar(插入数据库时遇到了一些问题。数据确实上传到了数据库,但我很难处理Python中的错误消息。

from datetime import datetime, date
import pytz
import psycopg2
import sqlalchemy
from pandas import DataFrame
from pvlive_api import PVLive
from sqlalchemy import create_engine, Integer, String, DATETIME, FLOAT

def insert_data():
""" Connect to the PostgreSQL database server """
# Calling the class from the pvlive_api.py file
data = PVLive()
# Gets the data between the two dates from the API and converts the output into a dataframe
dl = data.between(datetime(2019, 4, 5, 10, 30, tzinfo=pytz.utc),
datetime(2020, 4, 5, 14, 0, tzinfo=pytz.utc), entity_type="pes",
entity_id=0, dataframe=True)
# sql is used to insert the API data into the database table
sql = """INSERT INTO sheffield (pes_id, datetime_gmt, generation_mw) VALUES (%s, %s, %s)"""
uri = "Redacted"
print('Connecting to the PostgreSQL database...')
engine = create_engine(
'postgresql+psycopg2://Redacted')
# connect to the PostgreSQL server
conn = psycopg2.connect(uri)
# create a cursor that allows python code to execute Postgresql commands
cur = conn.cursor()
# Converts the data from a dataframe to an sql readable format, it also appends new data to the table, also
# prevents the index from being included in the table
into_db = dl.to_sql('sheffield', engine, if_exists='append', index=False)
cur.execute(sql, into_db)
# Commits any changes to ensure they actually happen
conn.commit()
# close the communication with the PostgreSQL
cur.close()

def main():
insert_data()

if __name__ == "__main__":
main()

我得到的错误如下:

psycopg2.errors.SyntaxError: syntax error at or near "%"
LINE 1: ...eld (pes_id, datetime_gmt, generation_mw) VALUES (%s, %s, %s...

^指向前%s。我假设这个问题是由于我在cur.execute((中使用into_db作为第二个参数造成的,但是,正如我前面提到的,数据仍然会上传到我的数据库中。正如我之前提到的,我对Python非常陌生,因此它可能是一个容易解决的问题,但我忽略了它。我还从代码中编辑了一些个人连接信息。任何帮助都将不胜感激,谢谢。

您收到这样的错误是因为试图在没有任何值可插入的情况下执行查询。

若在使用之前阅读了关于dl.to_sql的文档,就会知道该方法将记录写入数据库并返回None

因此,不需要尝试构建自己的sql查询来插入数据。

相关内容

最新更新