用python导入我的数据库连接

时间:2017-03-20 14:47:11

标签: python mysql

是否可以使用我的数据库凭据创建单个py文件,以连接到MySQL数据库Ex。

con = [ [ip='0.0.0.0'],[username = 'root'],
[password='pswd'],[database='test']]

然后在另一个文件上使用此文件。

喜欢

import dbcon.py*

dbcon.sort

con = mdb.connect(info from py file goes here.)

3 个答案:

答案 0 :(得分:6)

这是可能的,但混合代码和数据(任何类型 - 配置,HTML等)并不是一个好主意,至少有两个原因:

  • 设计 - 最终得到所谓的高耦合。存在大量依赖关系,难以遵循的情况,以及您的应用程序越来越难以修改。
  • 安全性 - 您的凭据迟早会在某些代码备份存档或存储库中结束。配置文件可以另外加密,py文件不是真的。如果它是一个Web应用程序,则更容易将访问单个配置文件限制为所有可能包含敏感数据的py文件。

您仍然可以创建这个易于使用的独立连接处理功能。但是将连接凭据移动到单独的配置文件中。

<强>的config.ini:

[mysqlDB]
host = '0.0.0.0'
db = 'test'
user = 'root'
pass = 'pswd'

您可以在连接py文件中读取配置或使其更全局(即单例?)。如果要读取连接文件中的配置:

<强> storage.py:

import configparser
import MySQLdb.cursors

config = configparser.ConfigParser()
config.read('config.ini')

def connect():
    return MySQLdb.connect(host = config['mysqlDB']['host'],
                           user = config['mysqlDB']['user'],
                           passwd = config['mysqlDB']['pass'],
                           db = config['mysqlDB']['db'])

用法示例:

import storage

conn = storage.connect()

答案 1 :(得分:-1)

  • 对于此示例,我是在 GitHub 上创建的,您可以在其中查看和运行代码。
  • 该测试提出了问题本身的解决方案,即如何包含来自第二个模块的连接,以及数据库的参数。
└──GitHub
   ├── config.ini
   ├── db_lib.py
   ├── python_mysql_dbconfig.py
   └── test.py

下面提供了一个较短的版本

首先创建一个名为config.ini的数据库配置文件,定义一个有四个参数的section,如下:

[mysql]
HOST     = 127.0.0.1
USER     = root
PASSWORD = root
DATABASE = db

其次,创建一个名为 python_mysql_dbconfig.py 的新模块,它 reads 来自 config.ini 文件的数据库配置并返回一个字典对象:

pip install configparser
from configparser import ConfigParser


def read_db_config(filename='config.ini', section='mysql'):
    """ Read database configuration file and return a dictionary object
    :param filename: name of the configuration file
    :param section: section of database configuration
    :return: a dictionary of database parameters
    """
    # create parser and read ini configuration file
    parser = ConfigParser()
    parser.read(filename)

    # get section, default to mysql
    db = {}
    if parser.has_section(section):
        items = parser.items(section)
        for item in items:
            db[item[0]] = item[1]
    else:
        raise Exception('{0} not found in the {1} file'.format(section, filename))

    return db

让我们测试这个模块:

# db_lib.py

from python_mysql_dbconfig import read_db_config

print(read_db_config())

输出:

{'host': '127.0.0.1', 'user': 'root', 'password': 'root', 'database': 'db'}

第三,在使用db_lib.py对象连接MySQLConnection数据库的python_mysql模块中(对测试的评论)。

from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config

# print(read_db_config())


def connect():
    """ Connect to MySQL database """

    db_config = read_db_config()
    conn = None
    try:
        print("Connecting to MySQL database...")
        conn = MySQLConnection(**db_config)

        if conn.is_connected():
            print("Connection established.")

            cursor = conn.cursor()
            cursor.execute("SELECT VERSION()")

            row = cursor.fetchone()
            print("Server version:", row[0])
        else:
            print("Connection failed.")

    except Exception as error:
        print(error)

    finally:
        if conn is not None and conn.is_connected():
            conn.close()
            print("Connection closed.")


if __name__ == "__main__":
    connect()

让我们更详细地检查模块:

  • 首先,导入必要的对象,包括 MySQLConnection - pip install mysql-connector-python、来自 MySQL Connector/Python 包的 Error 和来自 read_db_config 模块的 python_mysql_dbconfig
  • 其次,读取数据库配置并将其传递给 connect() 函数中创建 MySQLConnection 对象的新实例。

输出:

>python db_lib.py
Connecting to MySQL database...
Connection established.
Server version: 8.0.22
Connection closed.

注意

  • 还有其他驱动程序可以连接到底座,例如 PyMySQL
import pymysql

# Connect to the database
connection = pymysql.connect(host='localhost',
                             user='user',
                             password='passwd',
                             database='db')

python中的配置文件:

# Write data to a file:

import json

config = {"key1": "value1", "key2": "value2"}

with open('config1.json', 'w') as f:
    json.dump(config, f)


# Read data from a file:

import json

with open('config.json', 'r') as f:
    config = json.load(f)

#edit the data
config['key3'] = 'value3'

#write it back to the file
with open('config.json', 'w') as f:
    json.dump(config, f)
import yaml

with open("example.yaml", 'r') as stream:
    try:
        print(yaml.safe_load(stream))
    except yaml.YAMLError as exc:
        print(exc)
import os

os.getenv('DATABASE_NAME')
# Standard
from envparse import env

# Schema
from envparse import Env

env = Env(BOOLEAN_VAR=bool, LIST_VAR=dict(cast=list, subcast=int))

答案 2 :(得分:-1)

添加 database.py 文件:

import mysql.connector

db_conn = mysql.connector.connect(
    host='localhost',
    user='<username>',
    password='<password>',
    database='<database>'
)

然后像这样导入连接(您必须在与 database.py 相同的目录中执行此操作):

from database import db_conn

cursor = db_conn.cursor()
cursor.execute('SELECT * FROM test_table')