Я не уверен, почему возникает эта ошибка. В этом проекте у меня сначала есть файл yaml, содержащий учетные данные базы данных:
Код: Выделить всё
host: localhost
port: 5432
username: postgres
password: postgres
database: AirlineReports
driver: postgresql+psycopg2
Код: Выделить всё
def create_engine_from_creds():
"""
Creates a SQLAlchemy engine using database credentials stored in a YAML file.
Args:
None
Returns:
engine: SQLAlchemy engine object connected to the specified database.
"""
database_creds = yaml.safe_load(open("database_creds.yaml")) # Load database credentials from YAML file
engine = create_engine(f'{database_creds["driver"]}://{database_creds["username"]}:\
{database_creds["password"]}@{database_creds["host"]}:\
{database_creds["port"]}/{database_creds["database"]}') #creating the database engine from the credentials
try:
with engine.connect() as connection:
version = connection.execute(text("SELECT version();")).scalar()
print(version) # confirming connection by printing database version
except ConnectionError as e:
print(f"An Connection error has occured to the database : {e}") # if connection fails, print error message
return engine
Код: Выделить всё
Base = declarative_base()
class Airline(Base):
"""
Represents the Airline table in the database.
"""
__tablename__ = "Airline"
IATA = Column(String(2), primary_key=True) # e.g., "AA"
Airline = Column(String(100), nullable=False) # Airline name
Country = Column(String(100)) # Country of origin
Region = Column(String(100)) # Region (e.g., Europe, Asia)
Код: Выделить всё
from database_connection_utils import create_engine_from_creds
from create_classes_for_tables import Airline
import pandas as pd
def read_airline_data_into_table(csv_file_path):
"""
Reads airline data from a CSV file and inserts it into the Airline table in the database.
Args:
csv_file_path (str): Path to the CSV file containing airline data.
Returns:
None
"""
engine = create_engine_from_creds() # Create database engine
# Read CSV data into a DataFrame
airline_df = pd.read_csv(csv_file_path)
# Insert data into the Airline table
airline_df.to_sql(Airline.__tablename__, engine, if_exists='append', index=False)
print(f"Inserted {len(airline_df)} records into the Airline table.")
if __name__ == "__main__":
read_airline_data_into_table("airline.csv")
Если кто-нибудь может помочь, где я ошибаюсь?>
Подробнее здесь: https://stackoverflow.com/questions/798 ... r-postgres
Мобильная версия