Sample code to connect python with database

Connect Python with MySql

Python having feature to connect any of the database with the help of different database connection packages. Like to connect Python with MySql we can use mysql.connector package. Which can be downloaded from pip package of Python very easly. Here is the example of Python connection with MySQL.

import mysql.connector
mydb = mysql.connector.connect(

mycursor = mydb.cursor()
sql = “SELECT * FROM student”
myresult = mycursor.fetchall()

for x in myresult:

Here you need to import mysql.connector if already installed in your machine else you need to download and install using pip command. You can google it for installation process using pip. Once imported connector then you need to create connection using connect function by passing host, user, passwd and database name. Once the connection is ready you can call cursor and execute query on cursor. Once the function fetchall() called the result need to store in variable and at last iterate the result and get desire output. That’s it. You are done.

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>