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 5

Creating a Database in 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
Create a cursor

mycursor=con.cursor()

mycursor=con.cursor()

Step:5
Give SQL command and execute it.

We give SQL command to create DataBase and execute the SQL command using execute function of created cursor.

q1=”create database employee;”
mycursor.execute(q1)
print(“Employee database created”)

q1="create database employee;"
mycursor.execute(q1)
print("Employee database created")

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 create a database
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")
        mycursor=con.cursor()
        q1="create database employee;"
        mycursor.execute(q1)
        print("Employee database created")
except Error as e:
        print(e)

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