Skip to content Skip to sidebar Skip to footer

Connecting Python Program To Mysql Safely

I want to connect to MySQL from my python program using MySQLdb. I am worried because I need to put username and password in the .py in order to connect to MySQL database, as well

Solution 1:

First, make sure your MySQL user/password is different than your username and password.

Next, make a file called, say, config.py and place it in a directory in your PYTHONPATH:

USER='zzzzzzzz'PASS='xxxxxxxx'HOST='yyyyyyyy'MYDB='wwwwwwww'

Change the permissions on the file so only you (and root) can read it. For example, on Unix:

chmod 0600 /path/to/config.py

Now, when you write a script using MySQLdb you'd write

import config
connection = MySQLdb.connect(
    host = config.HOST, user = config.USER,
    passwd = config.PASS, db = config.MYDB)

So your username and password will not appear in any of your scripts.


You could also put config.py in an encrypted directory, and/or on a USB thumb drive, so the file is only accessible when the drive is mounted.

Post a Comment for "Connecting Python Program To Mysql Safely"