Python 3.6:Mysql / Class / Inhertance连接问题

时间:2017-10-04 10:09:41

标签: python mysql

我正在尝试使用python 3.6运行以下代码连接到数据库,我不确定我是否正确使用Python,我在配置文件中读取并创建了Dao的实例类并将配置详细信息传递回Dao的父类Db

当我尝试打开并关闭Dao对象上的连接时,它表示dbhost未设置。

非常感谢任何帮助。

错误

Traceback (most recent call last):
  File "parse.py", line 12, in <module>
    sources = daoObj.getSourceUrls()
  File "E:\classes\Dao.py", line 14, in getSourceUrls
    conn = super().open()
  File "E:\classes\Db.py", line 22, in open
    conn = pymysql.connect(dbhost, dbuser, dbpass, dbname);
NameError: name 'dbhost' is not defined

parse.py

import configparser
from classes.Dao import Dao

# Load configuration settings
config = configparser.ConfigParser()
config.read("./config.ini")

# Create instance of database class
daoObj = Dao(config)

# Test database connection
daoObj.test()

Dao.py

from classes.Db import Db

class Dao(Db):
    """Contains all SQL queries used for database interaction"""
    node = None

    def __init__(self, config):
        """Default constructor"""
        super().__init__(config)

    def getSourceUrls(self):
        conn = super().open()
        super().close(conn)

Db.py

import pymysql

class Db:
    """Database connection class, handles all opening and closing of MySQL database connections."""
    dbuser = None
    dbpass = None
    dbhost = None
    dbname = None

    def __init__(self, config):
        """Default constructor"""
        # Assign the database login credentials
        dbuser = config["DB"]["USER"]
        dbpass = config["DB"]["PASS"]
        dbhost = config["DB"]["HOST"]
        dbname = config["DB"]["DATABASE"]

    def open(self):
        """Open database connection."""
        conn = None
        try:
            conn = pymysql.connect(dbhost, dbuser, dbpass, dbname);
        except pymysql.err.InternalError as e:
            print("Error connecting to database.")
        return conn

    def close(self, conn):
        """Close passed in database connection"""
        conn.close()

的config.ini

[DB]
USER=username
PASS=password
HOST=127.0.0.l
DATABASE=database

0 个答案:

没有答案