python mysql

 step 1:- install xampp and run it and open any browser and type "localhost/phpmyadmin"

and then create database as "mydb"  and inside it create table customers with name and address column as shown below :-





mytest.py file code :-


import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  password="",
  database="mydb"
)

mycursor = mydb.cursor()

sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("omsir", "virarnagari 21")
mycursor.execute(sql, val)

mydb.commit()

print(mycursor.rowcount, "record inserted.") 


output:-


display table record :-


selectdatabase.py file code :-

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  password="",
  database="mydb"
)

mycursor = mydb.cursor()

mycursor.execute("SELECT * FROM customers")

myresult = mycursor.fetchall()

for x in myresult:
  print(x)

output:-

now to update record 

updatedatabase.py file code:-

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  password="",
  database="mydb"
)

mycursor = mydb.cursor()

sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'virarnagari 21'"

mycursor.execute(sql)

mydb.commit()

print(mycursor.rowcount, "record(s) affected")

output:-


to delete record :-

deletedatabase.py file code :-

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  password="",
  database="mydb"
)

mycursor = mydb.cursor()

sql = "DELETE FROM customers WHERE name = 'omsir'"


mycursor.execute(sql)

mydb.commit()

print(mycursor.rowcount, "record(s) affected")

output:-


Previous
Next Post »