Home > Back-end >  Error on Python DB Connection PostgreSQL (Module)
Error on Python DB Connection PostgreSQL (Module)

Time:09-28

Currently, I am learning about databases with Python.

I am trying to make postgresql database connection under the OOP paradigm. I followed all the steps from this article, but I got an error when I run my code.

All the code is the same, I just modified the database.ini file with my DB setting.

** database.ini code:

[postgresql]
host = localhost
port = 5432
database = dvdrental
user = postgres
password = 1234

** config.py code:

# import libraries
from configparser import ConfigParser
import configparser
from pathlib import Path

def get_project_root() -> Path:
    ''' Return project root folder '''
    return Path(__file__).parents[1]

def config(config_db):
    
    section = 'postgresql'
    
    config_file_path = 'config/'   config_db

    if (len(config_file_path) > 0 and len(section) > 0):
        # create an instance of ConfigParser class
        config_parser = ConfigParser()

        # read the configuration file
        config_parser.read(config_file_path)

        # if the configuration file contains the provided section name
        if(config_parser.has_section(section=section)):
            # read options of the sections
            config_params = config_parser.items(section=section)

            # convert the list object to a python dictionary object
            # define an empty dict
            db_conn_dict = {}

            # loop in the list
            for config_param in config_params:
                # get options key and value
                key = config_params[0]
                value = config_params[1]

                # add the key value pair in the dictionary object
                db_conn_dict[key] = value
            
            # get connection object use above dictionary object
            return db_conn_dict

** db_conn.py code:

# import libraries
import pandas as pd 
import psycopg2
from config.config import config

# take in a PostgreSQL table and outputs a pandas dataframe
def load_db_table(config_db, query):
    params = config(config_db)
    engine = psycopg2.connect(**params)
    data = pd.read_sql(query, con = engine)
    return data

** main.py code:

# import library
from src.data.db_conn import load_db_table
from config.config import get_project_root

# project root
PROJECT_ROOT = get_project_root()

# read database
df = load_db_table(config_db = 'database.ini', query = 'SELECT * FROM actor LIMIT 5')

print(df)

The problem is, when I run the program I got the error:

TypeError: connect() keywords must be strings
PS D:\ASUS\MY CODES PYTHON\Iochordxsyy\db_connection> python main.py
Traceback (most recent call last):
  File "main.py", line 9, in <module>
    df = load_db_table(config_db = 'database.ini', query = 'SELECT * FROM actor LIMIT 5')
  File "D:\ASUS\MY CODES PYTHON\Iochordxsyy\db_connection\src\data\db_conn.py", line 9, in load_db_table
    engine = psycopg2.connect(**params)
TypeError: connect() keywords must be strings

This is the message when I debugged my code:

Exception has occurred: TypeError
connect() argument after ** must be a mapping, not NoneType
  File "D:\ASUS\MY CODES PYTHON\Iochordxsyy\db_connection\src\data\db_conn.py", line 9, in load_db_table
    engine = psycopg2.connect(**params)
  File "D:\ASUS\MY CODES PYTHON\Iochordxsyy\db_connection\main.py", line 9, in <module>
    df = load_db_table(config_db = 'database.ini', query = 'SELECT * FROM actor LIMIT 5')

I have checked all the code is the same as the article but I have no ideas why the error still occurs. Do you have any ideas?

If you have any ideas/solutions, it will be much appreciated.

Thank you.

Credit: Thank you for the authors of the articles mentioned above.

CodePudding user response:

I think "username" keyword in database.ini must be "user".

** database.ini code:

[postgresql]
host = localhost
port = 5432
database = dvdrental
user = postgres
password = 1234

CodePudding user response:

[Solved]

Hi all, I got the answer. There is a mistake script on the config.ini file. I change the script from "config_params[]" to "config_param[]"

** the correct script:

...
key = config_param[0]
value = config_param[1]
...

Thank you for all the comments.

  • Related