UNIT5
UNIT5
Python MySQL
Python can be used in database applications.
MySQL Database
To be able to experiment with the code examples in this tutorial, you should have MySQL
installed on your computer.
Navigate your command line to the location of PIP, and type the following:
demo_mysql_test.py:
import mysql.connector
If the above code was executed with no errors, "MySQL Connector" is installed and ready to be
used.
Create Connection
Start by creating a connection to the database.
demo_mysql_connection.py:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
print(mydb)
Creating a Database
To create a database in MySQL, use the "CREATE DATABASE" statement:
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
mycursor = mydb.cursor()
If the above code was executed with no errors, you have successfully created a database.
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
for x in mycursor:
print(x)
Or you can try to access the database when making the connection:
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
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
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
If the above code was executed with no errors, you have now successfully created a table.
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SHOW TABLES")
for x in mycursor:
print(x)
Primary Key
When creating a table, you should also create a column with a unique key for each record.
We use the statement "INT AUTO_INCREMENT PRIMARY KEY" which will insert a unique
number for each record. Starting at 1, and increased by one for each record.
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mydb.commit()
Important!: Notice the statement: mydb.commit(). It is required to make the changes, otherwise
no changes are made to the table.
The second parameter of the executemany() method is a list of tuples, containing the data you
want to insert:
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.executemany(sql, val)
mydb.commit()
Get Inserted ID
You can get the id of the row you just inserted by asking the cursor object.
Note: If you insert more than one row, the id of the last inserted row is returned.
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mydb.commit()
Example
Select all records from the "customers" table, and display the result:
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)
Note: We use the fetchall() method, which fetches all rows from the last executed statement.
Selecting Columns
To select only some of the columns in a table, use the "SELECT" statement followed by the
column name(s):
Example
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)
The fetchone() method will return the first row of the result:
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
myresult = mycursor.fetchone()
print(myresult)
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Wildcard Characters
You can also select the records that starts, includes, or ends with a given letter or phrase.
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
This is to prevent SQL injections, which is a common web hacking technique to destroy or
misuse your database.
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute(sql, adr)
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:
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute(sql)
mydb.commit()
Important!: Notice the statement: mydb.commit(). It is required to make the changes, otherwise
no changes are made to the table.
Notice the WHERE clause in the DELETE syntax: The WHERE clause specifies which
record(s) that should be deleted. If you omit the WHERE clause, all records will be deleted!
This is to prevent SQL injections, which is a common web hacking technique to destroy or
misuse your database.
The mysql.connector module uses the placeholder %s to escape values in the delete statement:
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute(sql, adr)
mydb.commit()
Update Table
You can update existing records in a table by using the "UPDATE" statement:
Example
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()
Important!: Notice the statement: mydb.commit(). It is required to make the changes, otherwise
no changes are made to the table.
Notice the WHERE clause in the UPDATE syntax: The WHERE clause specifies which
record or records that should be updated. If you omit the WHERE clause, all records will be
updated!
This is to prevent SQL injections, which is a common web hacking technique to destroy or
misuse your database.
The mysql.connector module uses the placeholder %s to escape values in the delete statement:
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute(sql, val)
mydb.commit()
MySQL: Joins
This MySQL tutorial explains how to use MySQL JOINS (inner and outer) with syntax, visual
illustrations, and examples.
Description
MySQL JOINS are used to retrieve data from multiple tables. A MySQL JOIN is performed
whenever two or more tables are joined in a SQL statement.
So let's discuss MySQL JOIN syntax, look at visual illustrations of MySQL JOINS, and explore
MySQL JOIN examples.
Syntax
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column;
Visual Illustration
In this visual diagram, the MySQL INNER JOIN returns the shaded area:
The MySQL INNER JOIN would return the records where table1 and table2 intersect.
Example
This MySQL INNER JOIN example would return all rows from the suppliers and orders tables
where there is a matching supplier_id value in both the suppliers and orders tables.
Let's look at some data to explain how the INNER JOINS work:
We have a table called suppliers with two fields (supplier_id and supplier_name). It contains the
following data:
supplier_id supplier_name
10000 IBM
10001 Hewlett Packard
10002 Microsoft
10003 NVIDIA
We have another table called orders with three fields (order_id, supplier_id, and order_date). It
contains the following data:
If we run the MySQL SELECT statement (that contains an INNER JOIN) below:
The rows for Microsoft and NVIDIA from the supplier table would be omitted, since the
supplier_id's 10002 and 10003 do not exist in both tables. The row for 500127 (order_id) from
the orders table would be omitted, since the supplier_id 10004 does not exist in the suppliers
table.
Old Syntax
As a final note, it is worth mentioning that the MySQL INNER JOIN example above could be
rewritten using the older implicit syntax as follows (but we still recommend using the INNER
JOIN keyword syntax):
Syntax
SELECT columns
FROM table1
LEFT [OUTER] JOIN table2
ON table1.column = table2.column;
In some databases, the LEFT OUTER JOIN keywords are replaced with LEFT JOIN.
Visual Illustration
In this visual diagram, the MySQL LEFT OUTER JOIN returns the shaded area:
The MySQL LEFT OUTER JOIN would return the all records from table1 and only those
records from table2 that intersect with table1.
Example
This LEFT OUTER JOIN example would return all rows from the suppliers table and only those
rows from the orders table where the joined fields are equal.
If a supplier_id value in the suppliers table does not exist in the orders table, all fields in the
orders table will display as <null> in the result set.
Let's look at some data to explain how LEFT OUTER JOINS work:
We have a table called suppliers with two fields (supplier_id and supplier_name). It contains the
following data:
supplier_id supplier_name
10000 IBM
10001 Hewlett Packard
10002 Microsoft
10003 NVIDIA
We have a second table called orders with three fields (order_id, supplier_id, and order_date). It
contains the following data:
If we run the SELECT statement (that contains a LEFT OUTER JOIN) below:
The rows for Microsoft and NVIDIA would be included because a LEFT OUTER JOIN was
used. However, you will notice that the order_date field for those records contains a <null>
value.
Syntax
SELECT columns
FROM table1
RIGHT [OUTER] JOIN table2
ON table1.column = table2.column;
In some databases, the RIGHT OUTER JOIN keywords are replaced with RIGHT JOIN.
Visual Illustration
In this visual diagram, the MySQL RIGHT OUTER JOIN returns the shaded area:
The MySQL RIGHT OUTER JOIN would return the all records from table2 and only those
records from table1 that intersect with table2.
Example
This RIGHT OUTER JOIN example would return all rows from the orders table and only those
rows from the suppliers table where the joined fields are equal.
If a supplier_id value in the orders table does not exist in the suppliers table, all fields in the
suppliers table will display as <null> in the result set.
Let's look at some data to explain how RIGHT OUTER JOINS work:
We have a table called suppliers with two fields (supplier_id and supplier_name). It contains the
following data:
supplier_id supplier_name
10000 Apple
10001 Google
We have a second table called orders with three fields (order_id, supplier_id, and order_date). It
contains the following data:
If we run the SELECT statement (that contains a RIGHT OUTER JOIN) below:
The row for 500127 (order_id) would be included because a RIGHT OUTER JOIN was used.
However, you will notice that the supplier_name field for that record contains a <null> value.