Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

import my database connection with python

Tags:

python

mysql

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.)
like image 943
Brandon Avatar asked Mar 20 '17 14:03

Brandon


People also ask

How does Python connect to database connectivity?

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.

How do you access a database in Python?

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.

Can Python connect to database systems?

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.


1 Answers

It is possible, but it's not good idea to mix code and data (any kind - configuration, HTML etc), for at least two reasons:

  • Design - you end up with so called high coupling. Situation where there is a lot of dependencies, hard to follow, and your app is more and more difficult to modify.
  • Security - your credentials sooner or later end up in some code backup archive or repository. Config file can be additionally encrypted, py file not really. If it's a web app, it's easier to restrict access to single config file then to all py files that can have sensitive data.

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()
like image 130
rsm Avatar answered Sep 19 '22 00:09

rsm