Header Ads Widget

Responsive Advertisement

How to connect python with mysql server step by step


How to Connect to MySQL Database in Python 

This is the first question in our mind when we start a project in python with mysql database server. We just need to connect the database with python using pip install command.In this Article we will show how to connect the mysql server with our python program. You will also find the video which show you how to connect mysql server with python. You just need some simple steps to establish this connection. 


Install MySQL connector module Use the pip command to install MySQL connector Python. 

pip install mysql-connector-python

Import MySQL connector module Import using a import mysql.connector statement so you can use this module’s methods to communicate with the MySQL database. 

Use the connect() method 

Use the connect() method of the MySQL Connector class with the required arguments to connect MySQL. It would return a MySQLConnection object if the connection established successfully 

Use the cursor() method 

Use the cursor() method of a MySQLConnection object to create a cursor object to perform various SQL operations. 

Use the execute() method 

The execute() methods run the SQL query and return the result. 

Extract result using fetchall() 

Use cursor.fetchall() or fetchone() or fetchmany() to read query result. 

Close cursor and connection objects 

use cursor.close() and connection.close() method to close open connections after your work completes


PYTHON PROGRAM TO SHOW THE CONNECTION BETWEEN MYSQL AND PYTHON

import mysql.connector as myconnection 

connection= myconnection.connect(host='localhost',user='root',password='0000') 

if connection.is_connected(): 

      print("Your program successfully connected with MySQL") 

else: 

       print("Your program is not connected with MySQL")






Term used in this program: 

import mysql.connection : Is used to import library to python program

connection :  mysql object 

is_connected() : function used to check connection between python and mysql successful or Unsuccessful. connection.is_connected() return True when connection is successful and connection.is_connected() return False when connection is unsuccessful.

execute(): Execute function is used to execute the SQL query in python program 


Soon I will share video to show how to create connection between Mysql and Python. 




Post a Comment

0 Comments