Take the 2-minute tour ×

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 into inno setup.

Couldn't anybody find the user name and password and get access to my database? How do I solve this problem? Do I make a sql user with limited access somehow? (I am new to html/css/MySQL).

share|improve this question
ask for the user to input the user and pass instead of hard coding it. –  Serdalis Mar 13 '13 at 1:27
Make the file readable only by a certain user. If someone has root access to your computer, they're going to get your passwords. –  Blender Mar 13 '13 at 1:32
add comment

1 Answer

up vote 2 down vote accepted

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:


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.

share|improve this answer
add comment

Your Answer


