0% found this document useful (0 votes)
3 views2 pages

Python MySQL Connector Guide

Uploaded by

methaniradhika
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)
3 views2 pages

Python MySQL Connector Guide

Uploaded by

methaniradhika
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

Steps to Use Python–MySQL Connector

Step 1: Make sure MySQL server is running


Test in Terminal/Command Prompt:
mysql -u root -p

Step 2: Create or choose a database in MySQL (only once)


CREATE DATABASE school;
USE school;

CREATE TABLE Student (


RollNo INT PRIMARY KEY,
Name VARCHAR(30) NOT NULL,
Gender CHAR(1),
Marks FLOAT
);

Step 3: Write your Python program


import [Link]

# Connect
conn = [Link](
host="localhost",
user="root",
password="YOUR_PASSWORD",
database="school"
)

cursor = [Link]()

# Example: fetch data


[Link]("SELECT * FROM Student;")
for row in [Link]():
print(row)

# Example: insert new data


[Link](
"INSERT INTO Student (RollNo, Name, Gender, Marks) VALUES (%s, %s, %s, %s)",
(105, "Neha", "F", 88.0)
)
[Link]()

# Close
[Link]()
[Link]()

Step 4: Run the Python file


cd path/to/your/file
python3 mysql_connect.py

Step 5: Repeat usage


1. Ensure MySQL server is running.
2. Open Terminal → go to your Python file’s folder.
3. Run your Python program with:
python3 [Link]

Optional: Auto-increment RollNo


CREATE TABLE Student (
RollNo INT PRIMARY KEY AUTO_INCREMENT,
Name VARCHAR(30) NOT NULL,
Gender CHAR(1),
Marks FLOAT
);

# Python (no RollNo needed)


[Link]("INSERT INTO Student (Name, Gender, Marks) VALUES (%s, %s, %s)",
("Ankit", "M", 92.5))
[Link]()

You might also like