How to access MySQL database using Python

The basic steps in accessing a MySQL database is normally to connect, execute statement, fetch result, and then to close the connection. The following is the steps translated into Python codes;

# Import required module
import MySQLdb
 
# Connect
conn = MySQLdb.connect(host="localhost", port=3306, user="root", passwd="root123", db="mysql")
cursor = conn.cursor(  )
 
# Execute statement
stmt = "SELECT * FROM user"
cursor.execute(stmt)
 
# Fetch and output the result
result = cursor.fetchall(  )
print result
 
# Close connection
conn.close(  )

The requirement for this is to install the MySQLdb module for Python which is available from it’s project page at http://sourceforge.net/projects/mysql-python. The connect function creates a connection to the database based on the supplied parameters, and a cursor object is then created upon the connection object. The above example only show the execute and fetchall methods, and there many other available methods from the cursor object. The conn object calls the close method to close the connection to the MySQL server.