CS Phyton-SQL Connectivity
CS Phyton-SQL Connectivity
Index
1. Introduction
2. Objective
OBJECTIVE
To understand how to connect Python with SQL.
2. Establish a connection:
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="testdb"
)
cursor = conn.cursor()
PROGRAMS
Program 1: Connect to the Database
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="root",
password="password"
)
if conn.is_connected():
print("Connected to MySQL!")
cursor.execute("SHOW DATABASES")
for db in cursor:
print(db)
cursor.execute("USE sampledb")
print("Database switched!")
Program 12: Add a New Column
query = "SELECT name, age FROM students WHERE age > 20"
cursor.execute(query)
for row in cursor.fetchall():
print(row)
CONCLUSION
This project highlights the
fundamentals of Python and SQL
integration, demonstrating essential
database operations such as creating,
updating, and retrieving records.