Python Connecting to MySQL

From Lunarpages Web Hosting Wiki
Jump to: navigation, search

How do I connect to a MySQL database using Python?

First, import the MySQLdb module:

import MySQLdb

Next, create a connection object:

connection=MySQLdb.connect(host="localhost",db="<database_name>",user="<username>",passwd="<password>")

Finally, create a cursor object:

cursor=connection.cursor()

Use the 'execute' method on the 'cursor' object to submit SQL to the database.

Please note: LPCP accounts use an external MySQL server, so localhost will not work. Use the IP of the server instead, which can be located when logged into LPCP on the right side, next to DB Server.

Share |
Want to read this in another language?