Python Interface With MySQL

Python MySQL Introduction
Python MySQL Installation
Python MySQL Connection
Check Python MySQL Connections
Python MySQL Create Database
Python MySQL Drop Database
Python MySQL Create Table
Python MySQL Insert (Single Record)
Python MySQL Insert (Multiple Record)
Python MySQL Select
Python MySQL Update
Python MySQL Delete
Call MySQL Stored Procedure
Python MySQL Parameterized Query
Python MySQL Transactions

Python Interface With MySQL 4

checking Python MySQL Connection

Step:1
import required packages

import mysql.connector
from mysql.connector import Error

import mysql.connector
from mysql.connector import Error

Step:2
set up connection

con = mysql.connector.connect
(host=’localhost’,
user=’root’,
password=’ct’)

con = mysql.connector.connect
(host='localhost',
user='root',
password='ct')

Step:3
To check if connection is established or not

if(con.is_connected()==True):
         print(“connected to MYSQL Database”)

if connection is established then message “connected to MYSQL Database” is displayed. Otherwise error message is displayed.

In case of ay error except: part of the program gets executed and error gets displayed.

except Error as e:
        print(e)

if(con.is_connected()==True):
        print("connected to MYSQL Database")

statements
statements

except Error as e:
        print(e)

Step:4
Finally the database connection is closed.

 

finally:
        if con is not None and con.is_connected():
            con.close()
            print("Connection closed")

Full Code:

#to check the connection
import mysql.connector
from mysql.connector import Error
con=None
try:
    con = mysql.connector.connect(host='localhost',user='root',password='ct')
    if(con.is_connected()==True):
        print("connected to MYSQL Database")

except Error as e:
        print(e)

finally:
        if con is not None and con.is_connected():
            con.close()
            print("Connection closed")

Visitor Counter

0051140