Python with Mysql

Connect Python with MySql

Python is having very good support to connect any database. The most popular database used is mysql. Here is the example to connect Python mysql.

  1. You need to download mysql-connector from https://pypi.org from your command prompt.
  2. In command prompt type command pip install mysql-connector and wait till the package is getting install. After completion of installation you will get message “Successfully installed mysql-connector-2.1.6
  3. If pip is not working in command prompt then you need to set the path of python script and python installation folder into environment variable of your computer.
  4. Open idle prompt and check the import of mysql-connector by using import statement (import mysql.connector as mycon)
  5. If you are not getting any exception from Python Interpreter then your system is ready with mysql-connector to connect Python with mysql.

This is how you can download the connector from pip and test it. Now the next step to test the connection of python with mysql. Here is the program to test and get data from mysql in python console.

Program to test Python connection with MySql Database

Output of above program will be

(1, ‘Akash’, ‘teacher’, 1, Decimal(‘20000’), Decimal(‘1200’), 1)
(2, ‘Suraj’, ‘teacher’, 2, Decimal(‘23000’), Decimal(‘1300’), 2)
(3, ‘Aman’, ‘prof’, 3, Decimal(‘30000’), Decimal(‘2000’), 4)
(4, ‘Rakesh’, ‘businesman’, 4, Decimal(‘40000’), Decimal(‘3000’), 3)

Customizing to the output as your requirement – You can customize the output as per your requirement. Here I have iterated the output in two loops. First loop is to get row from cursor and second loop is to get individual elements from the row. So variable a will have row data and variable b will have every element of the row. Lets look into the for loop.

Data iteration from the cursor object.

Output of above program will be

1 Akash teacher 1 20000 1200 1
2 Suraj teacher 2 23000 1300 2
3 Aman prof 3 30000 2000 4

One thought on “Python with Mysql

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>