0% found this document useful (0 votes)
20 views

MYSQL

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

MYSQL

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 44

Python MySQL

MySQL Database

https://www.mysql.com/downloads/.
Install MySQL Driver

• Python needs a MySQL driver to access the MySQL


database.

python -m pip install mysql-connector-python


Test MySQL Connector

• import mysql.connector

if this page is executed with no errors, you have the


"mysql.connector" module installed.
Create Connection

• tart by creating a connection to the database.


• Use the username and password from your MySQL database:

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)

print(mydb)

<mysql.connector.connection.MySQLConnection object ar
0x016645F0>
Python MySQL Create Database
• Creating a Database
• To create a database in MySQL, use the "CREATE
DATABASE" statement:
Example:
• create a database named "mydatabase":

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="myusername",
password="mypassword"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE DATABASE mydatabase")


Check if Database Exists
• You can check if a database exist by listing all databases in your system by using the "SHOW DATABASES"
statement:
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="myusername",
password="mypassword"
)

mycursor = mydb.cursor() ('information_scheme',)


('mydatabase',)
mycursor.execute("SHOW DATABASES") ('performance_schema',)
('sys',)
for x in mycursor:
print(x)
Python MySQL Create Table
• Creating a Table
• To create a table in MySQL, use the "CREATE TABLE"
statement.

Make sure you define the name of the database


when you create the connection
Example

Create a table named "customers":


import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
password="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")

#If this page is executed with no error, you have successfully created a table named
"customers".
Check if Table Exists
• You can check if a table exist by listing all tables in your database with the
"SHOW TABLES" statement:

import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
password="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SHOW TABLES")

for x in mycursor: ('customers',)


print(x)
Primary Key
• When creating a table, you should also create a column
with a unique key for each record.
• This can be done by defining a PRIMARY KEY.
Example
Create primary key when creating the table:

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()

mycursor.execute("CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name


VARCHAR(255), address VARCHAR(255))")
#If this page is executed with no error, the table "customers" now has a primary key
If the table already exists, use the ALTER TABLE keyword:

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

mycursor = mydb.cursor()
mycursor.execute("ALTER TABLE customers ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY")

#If this page is executed with no error, the table "customers" now has a primary key
Python MySQL Insert Into Table

• 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()

sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"


val = ("John", "Highway 21")
mycursor.execute(sql, val)

mydb.commit()

print(mycursor.rowcount, "record inserted.")


Insert Multiple Rows
• To insert multiple rows into a table, use the executemany() method.

• The second parameter of the executemany() method is a list of tuples,


containing the data you want to insert:
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

mycursor = mydb.cursor()

sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"


val = [
('Peter', 'Lowstreet 4'),
('Amy', 'Apple st 652'),
('Hannah', 'Mountain 21'),
('Michael', 'Valley 345'),
('Sandy', 'Ocean blvd 2'),
('Betty', 'Green Grass 1'),
('Richard', 'Sky st 331'),
('Susan', 'One way 98'),
('Vicky', 'Yellow Garden 2'),
('Ben', 'Park Lane 38'),
('William', 'Central st 954'),
('Chuck', 'Main Road 989'),
('Viola', 'Sideway 1633')
]

mycursor.executemany(sql, val)

mydb.commit()

print(mycursor.rowcount, "was inserted.")


Python MySQL Select From
• Select From a Table
• To select from a table in MySQL, use the "SELECT"
statement:
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("SELECT * FROM customers")

myresult = mycursor.fetchall()

for x in myresult:
print(x)
Selecting Columns
• import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("SELECT name, address FROM customers")

myresult = mycursor.fetchall()

for x in myresult:
print(x)
Using the fetchone() Method
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="myusername",
password="mypassword",
database="mydatabase"
)

mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchone()
(1, 'John', 'Highway 21')
print(myresult)
Select With a Filter

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

mycursor = mydb.cursor()

sql = "SELECT * FROM customers WHERE address ='Park Lane 38'"

mycursor.execute(sql)

myresult = mycursor.fetchall()

for x in myresult:
print(x)
Python MySQL Order By
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

mycursor = mydb.cursor()

sql = "SELECT * FROM customers ORDER BY name"

mycursor.execute(sql)

myresult = mycursor.fetchall()

for x in myresult:
print(x)
ORDER BY DESC

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

mycursor = mydb.cursor()

sql = "SELECT * FROM customers ORDER BY name DESC"

mycursor.execute(sql)

myresult = mycursor.fetchall()

for x in myresult:
print(x)
Python MySQL Delete

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

mycursor = mydb.cursor()

sql = "DELETE FROM customers WHERE address = 'Mountain 21'"

mycursor.execute(sql)

mydb.commit()

print(mycursor.rowcount, "record(s) deleted")


Another Example
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="myusername",
password="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "DELETE FROM customers WHERE address = %s"
adr = ("Yellow Garden 2", )
mycursor.execute(sql, adr)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted")
Python MySQL Drop Table

• Delete a Table
• You can delete an existing table by using the "DROP
TABLE" statement:
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

mycursor = mydb.cursor()

sql = "DROP TABLE customers"

mycursor.execute(sql)
Drop Only if Exist
• If the table you want to delete is already deleted, or for
any other reason does not exist, you can use the IF
EXISTS keyword to avoid getting an error.
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

mycursor = mydb.cursor()

sql = "DROP TABLE IF EXISTS customers"

mycursor.execute(sql)
Python MySQL Update Table

• Update Table
• You can update existing records in a table by using the
"UPDATE" statement:
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

mycursor = mydb.cursor()

sql = "UPDATE customers SET address = 'Canyon 123' WHERE


address = 'Valley 345'"

mycursor.execute(sql)

mydb.commit()

print(mycursor.rowcount, "record(s) affected")


• import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

mycursor = mydb.cursor()

sql = "UPDATE customers SET address = %s WHERE address = %s"


val = ("Valley 345", "Canyon 123")

mycursor.execute(sql, val)

mydb.commit()

print(mycursor.rowcount, "record(s) affected")


Python MySQL Limit
• Example
Select the 5 first records in the "customers" table:
• import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("SELECT * FROM customers LIMIT 5")

myresult = mycursor.fetchall() (1, 'John', 'Highway 21')


(2, 'Peter', 'Lowstreet 27')
(3, 'Amy', 'Apple st 652')
for x in myresult: (4, 'Hannah', 'Mountain 21')
print(x) (5, 'Michael', 'Valley 345')
• Start From Another Position
• If you want to return five records, starting from the third record, you can
use the "OFFSET" keyword:
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("SELECT * FROM customers


LIMIT 5 OFFSET 2")
(3, 'Amy', 'Apple st 652')
myresult = mycursor.fetchall() (4, 'Hannah', 'Mountain 21')
(5, 'Michael', 'Valley 345')
for x in myresult: (6, 'Sandy', 'Ocean blvd 2')
print(x) (7, 'Betty', 'Green Grass 1')
Python MySQL Join

• Join Two or More Tables


• You can combine rows from two or more tables, based
on a related column between them, by using a JOIN
statement.
• Consider you have a "users" table and a "products"
table:
users

{ id: 1, name: 'John', fav: 154},


{ id: 2, name: 'Peter', fav: 154},
{ id: 3, name: 'Amy', fav: 155},
{ id: 4, name: 'Hannah', fav:},
{ id: 5, name: 'Michael', fav:}
products
{ id: 154, name: 'Chocolate Heaven' },
{ id: 155, name: 'Tasty Lemons' },
{ id: 156, name: 'Vanilla Dreams' }
Example
Join users and products to see the name of the users favorite
product:

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

mycursor = mydb.cursor()

sql = "SELECT \
users.name AS user, \
products.name AS favorite \
FROM users \
INNER JOIN products ON users.fav = products.id"

mycursor.execute(sql)
('John', 'Chocolate Heaven')
myresult = mycursor.fetchall() ('Peter', 'Chocolate Heaven')
for x in myresult: ('Amy', 'Tasty Lemon')
print(x)
LEFT JOIN
In the example above, Hannah, and Michael were excluded from the result, that
is because INNER JOIN only shows the records where there is a match.
If you want to show all users, even if they do not have a favorite product, use
the LEFT JOIN statement:

sql = "SELECT \
users.name AS user, \
products.name AS favorite \
FROM users \
LEFT JOIN products ON users.fav = products.id“
mycursor.execute(sql)
myresult = mycursor.fetchall()
('John', 'Chocolate Heaven')
for x in myresult: ('Peter', 'Chocolate Heaven')
('Amy', 'Tasty Lemon')
print(x) ('Hannah', None)
('Michael', None)
RIGHT JOIN
If you want to return all products, and the users who have them as
their favorite, even if no user have them as their favorite, use the
RIGHT JOIN statement:

sql = "SELECT \
users.name AS user, \
products.name AS favorite \
FROM users \
RIGHT JOIN products ON users.fav =
products.id“
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
THANK
S

You might also like