0% found this document useful (0 votes)
12 views4 pages

Python MySQL Interaction Tutorial

Uploaded by

luffyop915
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)
12 views4 pages

Python MySQL Interaction Tutorial

Uploaded by

luffyop915
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

a simple Python program that uses embedded SQL to interact with a MySQL table (say,

student(reg_no, name, year, GPA)).

CREATE DATABASE college;

USE college;

CREATE TABLE student (

reg_no INT PRIMARY KEY,

name VARCHAR(100),

year INT,

GPA DECIMAL(3,2)

);

Python code:

import [Link]

# Step 1: Connect to MySQL

conn = [Link](

host="localhost", # MySQL server (change if needed)

user="root", # MySQL username

password="yourpassword", # MySQL password

database="college" # Database name

)
cursor = [Link]()

# Step 2: Insert a record

insert_query = "INSERT INTO student (reg_no, name, year, GPA) VALUES (%s, %s, %s, %s)"

student_data = (101, "Alice", 2, 8.5)

[Link](insert_query, student_data)

[Link]() # Save changes

print(" Record Inserted!")

# Step 3: Fetch and display all records

[Link]("SELECT * FROM student")

rows = [Link]()

print("\nStudent Records:")

for row in rows:

print(f"RegNo: {row[0]}, Name: {row[1]}, Year: {row[2]}, GPA: {row[3]}")

# Step 4: Close connection

[Link]()

[Link]()

[Link]() → Connects Python with MySQL.

[Link](query, values) → Runs SQL inside Python (this is embedded SQL


[Link]() → Saves changes (for INSERT UPDATE DELETE

[Link]() → Retrieves all rows from SELECT

Dynamic SQL:

import [Link]

# Step 1: Connect to database

conn = [Link](

host="localhost",

user="root",

password="yourpassword",

database="college"

cursor = [Link]()

# Step 2: Dynamic SQL - query built at runtime

table_name = "student"

column_name = "year"

year_value = 2

query = f"SELECT reg_no, name, GPA FROM {table_name} WHERE {column_name} = {year_value}"
# Step 3: Execute the dynamically built query

[Link](query)

# Step 4: Fetch and display results

print("Student Records (Year =", year_value, "):")

for row in [Link]():

print(f"RegNo: {row[0]}, Name: {row[1]}, GPA: {row[2]}")

# Step 5: Close

[Link]()

[Link]()

You might also like