database connectivity in python code example

Example 1: python project with database connectivity

#APPARENTLY IT IS NOT POSSIBLE TO UPLOAD TOO LONG CODES HERE
# AND MY PROJECT IS OVER 1800 LINES DISTRIBUTED OVER 3 FILES... SO
# HERE ARE THE BASICS... HOPE YOU CAN BUILD UP YOUR OWN PROJECT USING THIS
# THIS IS AN EXAMPLE JUST EXPLAINING THE BASICS OF DATABASE MANNAGEMENT IN PYTHON
# HOPE YOU CAN BUILD UP FROM HERE
import mysql.connector as MC
try:
    Con_o = MC.connect(host="localhost",user="root",passwd="sidspc12345",database="mydb")
    if Con_o.is_connected():
        print("Connection established successfully")
except Exception as E:
    print("Connection Failed !")
    print("ERROR : ",e)

Cur = Con_o.cursor()
Cur.execute("select * from  students where Percentage>= 95")

data = Cur.fetchall()

for row in data:
    print(row)

Con_o.commit()
st = "INSERT INTO students(Roll,Name,Sex,Stream,Phone,Address,Maths,Science,SST,English,Hindi) values({},'{}','{}','{}',{},'{}',{},{},{},{},{})".format(11021,'Siddharth','M','S',7002744892,'Second link road Silchar',100,100,100,94,88)
Cur.execute(st)
Con_o.commit()

Cur.execute("select * from  students")

data = Cur.fetchall()

for row in data:
    print(row)
Con_o.close()

Example 2: connect python to mysql

import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  port = 8888, #for Mamp users
  database='whatever db you want'
)
print(mydb)

Example 3: mysql connection python

from sqlalchemy import types, create_engine
import pymysql

try:
	conn = create_engine('mysql+pymysql://user:pass@IP/database_name')
  	print("MySQL Connection Sucessfull!!!!!!!!!!!")

except Exception as err:

	print("MySQL Connection Failed !!!!!!!!!!!")
	print(err)