is It possible to create a single py file with my database credentials for connecting to MySQL database Ex.
con = [ [ip='0.0.0.0'],[username = 'root'],
[password='pswd'],[database='test']]
And then use this file on another file.
like
import dbcon.py*
dbcon.sort
con = mdb.connect(info from py file goes here.)
To create a connection between the MySQL database and Python, the connect() method of mysql. connector module is used. We pass the database details like HostName, username, and the password in the method call, and then the method returns the connection object.
To access databases in Python, you'll need to use a database adapter. Python offers database adapters through its modules that allow access to major databases such as MySQL, PostgreSQL, SQL Server, and SQLite. Furthermore, all of these modules rely on Python's database API (DB-API) for managing databases.
Python supports relational database systems. Python database APIs are compatible with various databases, so it is very easy to migrate and port database application interfaces.
It is possible, but it's not good idea to mix code and data (any kind - configuration, HTML etc), for at least two reasons:
You can still create this separate, easy to use, connection handling function. But move your connection credentials to separate configuration file.
config.ini:
[mysqlDB]
host = '0.0.0.0'
db = 'test'
user = 'root'
pass = 'pswd'
You can read configuration in your connection py file or make it more global (ie singleton?). If you want to read configuration in connection file:
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'])
Usage example:
import storage
conn = storage.connect()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With