Reply to comment

Python MySQL Getting-Started on Linux

  1. Installation
  2. Connection
  3. Insertion
  4. Query


Prerequisite: Setuptools and Pip Installed for your Python platform

To Getting-Started working with MySQL in Python you need to have Installed the Module MySQL-python.

Before to install the MySQL-Python Module you need to Install the Dependency: libmysql-dev.

On Debian and Ubuntu you simply perform:

sudo apt-get install libmysql-dev

After you can use the Pip to Manage the MySQL-Python installation with:

sudo pip install mysql-python


To Connect by Python to your MySQL Database in the Shell or by a Script:
>> import MySQLdb as mysql
>> db = mysql.connect("localhost", "userName", "password", "dbName")


Next if you want to Insert or Query the Database you need first Set a "cursor" like:

kursor = db.cursor()

To Insert one Row of Data into your Database:


"INSERT INTO tableName (colName1, ..., colNameN) VALUES (%s, ..., %s)",

( value1, ..., valueN)


To Insert Multiple Rows of Data in the Database:


"INSERT INTO tableName (colName1, ..., colNameN) VALUES (%s, ..., %s)",

( value11, ..., value1N),
( valueM1, ..., valueMN)



The cursor Command Syntax to Query MySQL Similarly:

>> searchS = "dan"

"SELECT * FROM tableName WHERE first_name LIKE %s",


Remember to Add a "," after the last Parameter Variable given because is needed by MySQL-Python.

Where are the Query Results? Right Inside the "cursor" and I will show you How to Get them Out...

>> queryR = kursor.fetchone()
>> print queryR



Theme by Danetsoft and Danang Probo Sayekti inspired by Maksimer