How to use Python to connect to a database
Using python, you can connect and run queries against a MySQL database on your server.
In this example, we've created a test script named test_db.py and placed it in our cgi-bin folder. We also updated the file's permissions to 755.
We also used the following settings within the code:
- database name: inmoti6_pytest
- database user: inmoti6_pytest
- database password: pytest
- database host: localhost
We're connecting to the database and running SELECT VERSION(), which shows us which version of MySQL we are running.
# connect to the database
db = MySQLdb.connect("localhost","inmoti6_pytest","pytest","inmoti6_pytest" )
# setup a cursor object using cursor() method
cursor = db.cursor()
# run an 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
When viewing this page in our browser, we see:
Database version : 5.0.92-community-log
We value your feedback!
There is a step or detail missing from the instructions.
The information is incorrect or out-of-date.
It does not resolve the question/problem I have.
Post a Comment
Do you want to publish a tutorial to our support center?