0% found this document useful (0 votes)
6 views3 pages

Python MySQL Database Operations Guide

Uploaded by

regitaraja
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views3 pages

Python MySQL Database Operations Guide

Uploaded by

regitaraja
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON DATABASE CONNECTIVITY

Query to create a database and a table in MySQL:


CREATE DATABASE college;

USE college;

CREATE TABLE students (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
age INT
);
Use: “pip install mysql-connector” to install the required python
package.
[Link]:
import [Link]

db = [Link](host="[Link]", user="root", passwd


= "", database="college")

name = input("Enter your name: ")


age = int(input("Enter your age: "))

cur = [Link]()

[Link]("INSERT INTO students (name, age) values(%s, %s)",


(name, age,))
[Link]()

[Link]
import [Link]

db = [Link](host="[Link]", user="root",
passwd = "", database="college")
cur = [Link]()
[Link]("SELECT * FROM students;")
students = [Link]()
print(type(students))

for student in students:


print(type(student))
[Link]
import [Link]

db = [Link](host="[Link]", user="root",
passwd = "", database="college")
cur = [Link]()

print("Which Record do you want to update??")

[Link]("SELECT * FROM students;")


students = [Link]()

for student in students:


print(student)

studid = int(input("Enter the ID to UPDATE: "))


name = input("Enter the new NAME: ")

[Link]("UPDATE students set name = %s WHERE id = %s",


(name, studid))
[Link]()

print([Link], " rows affected.")


[Link]
import [Link]

db = [Link](host="[Link]", user="root",
passwd="", database="college")

cur = [Link]()

[Link]("SELECT * FROM students;")


students = [Link]()

print("Current Records:")
for student in students:
print(student)

studid = int(input("Enter the ID to DELETE: "))

[Link]("DELETE FROM students WHERE id = %s", (studid,))


[Link]()

if [Link] > 0:
print(f"Record with ID {studid} deleted successfully.")
else:
print(f"No record found with ID {studid}.")

You might also like