我正在尝试使用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
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()
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)
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()
[DB]
USER=username
PASS=password
HOST=127.0.0.l
DATABASE=database