Image

Python

How to install pip on Ubuntu and Debian

By  •  Python

Both Ubuntu and Debian provide Python modules in their apt repositories, but it doesn't host the less popular modules. The version of the available Python modules is also tied …
Read More

How to install pip on CentOS / Red Hat / Fedora

By  •  Python

Python modules for CentOS, Red Hat, or Fedora are available in their yum repositories, but they don't have as many as those hosted in Python Package Index (PyPI). PyPI
Read More

How to access MySQL database using Python

By  •  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.

Top