Python MySQL
Python MySQL
Computing/Information System
• MySQL server
• MySQL connector.
• MySQL server will provide all the services required for handling your database.
• Once the server is up and running, you can connect your Python application
with it using MySQL Connector/Python.
Installing MySQL Connector/Python
• This function takes in parameters like host, user, and password and returns a
MySQLConnection object.
• You can receive these credentials as input from the user and pass them to
connect():
import mysql.connector
from mysql.connector import Error
try:
connection = mysql.connector.connect(
host=“localhost",
user=“root”,
password=“1234",
database=“Company"
)
if connection.is_connected():
print("Connected to MySQL database")
except Error as e:
print("Error while connecting to MySQL:", e)
Create Database
mydb = mysql.connector.connect(
host="localhost“,
user="yourusername",
password="yourpassword"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mydatabase")
Create a Table
Create a table named "customers":
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address
VARCHAR(255))")
Insert Into Table
• To fill a table in MySQL, use the "INSERT INTO" statement.
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password=
"yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Delete Record
• You can delete records from an existing table by using the "DELETE FROM" statement:
Delete any record where the address is "Mountain 21":
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()