【问题标题】:Error on Python DB Connection PostgreSQL (Module)Python DB 连接 PostgreSQL 错误(模块)
【发布时间】:2021-11-19 08:19:40
【问题描述】:

目前,我正在使用Python 学习数据库。

我正在尝试在 OOP 范式下建立 postgresql 数据库连接。 我按照article 中的所有步骤操作,但运行代码时出现错误。

所有代码都是一样的,我只是用我的数据库设置修改了database.ini 文件。

**database.ini代码:

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

**config.py代码:

# 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代码:

# 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代码:

# 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)

问题是,当我运行程序时,我得到了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

这是我debugged我的代码时的消息:

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')

我检查了所有代码都与文章相同,但我不知道为什么仍然会出现错误。你有什么想法吗?

如果您有任何想法/解决方案,我们将不胜感激。

谢谢。

信用: 感谢上述文章的作者。

【问题讨论】:

  • 如果你打印params,你会得到什么? edit 显示输出的问题。
  • 嗨,@snakecharmerb 谢谢你的评论。我已经知道错误的来源。 config.ini 有错误 --> "config_params[]"。它应该是“config_param[]”。谢谢你的cmets。非常感谢。

标签: python database postgresql psycopg2


【解决方案1】:

对齐this:config.py的缩进,如下图。

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

【讨论】:

    【解决方案2】:

    [已解决]

    大家好,我得到了答案。 config.ini 文件中有错误脚本。 I change the script from "config_params[]" to "config_param[]"

    ** 正确脚本:

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

    感谢所有的cmets。

    【讨论】:

      【解决方案3】:

      我认为 database.ini 中的“username”关键字必须是“user”。

      ** database.ini 代码:

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

      【讨论】:

      • 嗨@Muhammed YILMAZ 谢谢你的评论。我已经从用户名修改为用户,但仍然出现错误。但是,感谢您纠正我的错误。
      • config/目录下是否有config.py和database.ini文件?
      • 是的,这两个文件(config.py和database.ini)在config/目录下。
      • 文档 (psycopg.org/docs/module.html) 展示了如何使用连接功能。您可以尝试输入 manuel,而不是从 database.ini 文件中获取数据库信息。如果连接建立没有任何问题,你可以打印 config.config() 函数的返回值,即 params 变量,并检查它是否与你手动给的值不同。
      • "database" 用于 database.ini 文件中的数据库名称。我认为它也应该是“dbname”,但我不确定
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-05
      • 2013-10-26
      • 1970-01-01
      • 2015-12-13
      • 2016-10-02
      • 2016-04-15
      • 2013-02-27
      相关资源
      最近更新 更多