python - MySQL
# Python-MySQL Integration:
# Lab-1 [to create DB and show all DBs]
import mysql.connector
mydb=mysql.connector.connect(host="localhost", user="root", password="xxxxxxx")
print(mydb)
mycursor = mydb.cursor()
#mycursor.execute("create database poojasqldb")
mycursor.execute("show databases") # it will display all DBs
for x in mycursor:
print(x)
# Lab-2 [to create Table and show all Tables of that specific DB]
import mysql.connector
mydb=mysql.connector.connect(host="localhost", user="root", password="xxxxxxx", database="nnsql")
print(mydb)
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(50), address VARCHAR(255), state VARCHAR(30), pincode int(6), phone int(11))")
# it will create table named as "customers"
mycursor.execute("CREATE TABLE suppliers (name VARCHAR(50), address VARCHAR(255), state VARCHAR(30), pincode int(6), phone int(11))")
# it will create table named as "suppliers"
mycursor.execute("show tables")
for x in mycursor:
print(x)
# Lab-3 [to Insert values into Table]
import mysql.connector
mydb=mysql.connector.connect(host="localhost", user="root", password="xxxxxxx", database="nnsql")
print(mydb)
mycursor = mydb.cursor()
sql = "insert into customers(name,address,state,pincode,phone) values(%s,%s,%s,%s,%s)"
val=("Gopi","MG Nagar, Mumbai", "Maharastra", "442001", "928765043")
mycursor.execute(sql, val)
db.commit()
print(mycursor.rowcount, "record inserted")
sql1= "insert into suppliers(name,address,state,pincode,phone) values(%s,%s,%s,%s,%s)"
val1=("Vijay","MG Nagar, Delhi", "New delhi", "112422", "928765908")
mycursor.execute(sql1, val1)
mydb.commit()
print(mycursor.rowcount, "record inserted")
print("These are Table Content")
mycursor.execute("select * from customers")
for x in mycursor:
print(x)
mycursor.execute("select * from suppliers")
for x in mycursor:
print(x)
# Note: below screeshot is just for reference how output will comes,
# some names, values may vary since given diff names during execution
sfbjakdf
sfjafdja
jdfsfs
asfsakfkdsh
Note: