是否可以使用我的数据库凭据创建单个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.)
答案 0 :(得分:6)
这是可能的,但混合代码和数据(任何类型 - 配置,HTML等)并不是一个好主意,至少有两个原因:
您仍然可以创建这个易于使用的独立连接处理功能。但是将连接凭据移动到单独的配置文件中。
<强>的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
├── 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.
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')