24/7 U.S. Support – 877-595-4482
While most users will not have a need to use Python to connect to their MySQL database, there have been a few times when we've had questions about how to do that with Python.
At this point in the process you should already created a MySQL database and have a user assigned to that database.
You will need the following settings for your script. Please note that the settings we are including below are for our testing purposes, please replace these with your settings (database host should stay the same).
database name: whhsup5_python
database user: whhsup5_python
database password: pytest
database host: localhost
Once we have the database setup, we can create our script and save it to the cgi-bin folder as pythontest.py (name your file however you like, just remember the .py extension). Once the file has been created, change the fle permissions to 755 (as all files in the cgi-bin should be).
This script will connect to and run the SELECT VERSION(), command which will show us what version of MySQL our database is running.
# connect to the database
db = MySQLdb.connect("localhost","whhsup5_python","pytest","whhsup5_python" )
# setup a cursor object using cursor() method
cursor = db.cursor()
# run a sql question
# grab one result
data = cursor.fetchone()
# begin printing data to the screen
print "Content-Type: text/html"
<title>Python - Hello World</title>
print "Database version : %s " % data
# close the mysql database connection
Now, let's bring up pythontest.py in a browser and we should see:
Congratulations, you've just used Python to connect to your MySQL database!
|Email:||support@WebHostingHub.com||Ticket:||Submit a Support Ticket|
|Chat:||Click To Chat Now|