0% found this document useful (0 votes)
14 views21 pages

UNIT5

Uploaded by

parinlimbad6
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)
14 views21 pages

UNIT5

Uploaded by

parinlimbad6
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
You are on page 1/ 21

BCA SEM – 5 UNIT : - 5

Python MySQL
Python can be used in database applications.

One of the most popular databases is MySQL.

MySQL Database
To be able to experiment with the code examples in this tutorial, you should have MySQL
installed on your computer.

You can download a free MySQL database at https://www.mysql.com/downloads/.

Install MySQL Driver


Python needs a MySQL driver to access the MySQL database.

In this tutorial we will use the driver "MySQL Connector".

We recommend that you use PIP to install "MySQL Connector".

PIP is most likely already installed in your Python environment.

Navigate your command line to the location of PIP, and type the following:

Python –m pip install mysql.connector


C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>python -m pip install
mysql.connector

Now you have downloaded and installed a MySQL driver.

Test MySQL Connector


To test if the installation was successful, or if you already have "MySQL Connector" installed,
create a Python page with the following content:

demo_mysql_test.py:

import mysql.connector

1|P ag e PREPARED BY :- RADADIYA JITENDRA


BCA SEM – 5 UNIT : - 5

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.

Use the username and password from your MySQL 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

create a database named "mydatabase":

import mysql.connector

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

mycursor = mydb.cursor()

mycursor.execute("CREATE DATABASE mydatabase")

If the above code was executed with no errors, you have successfully created a database.

2|P ag e PREPARED BY :- RADADIYA JITENDRA


BCA SEM – 5 UNIT : - 5

Check if Database Exists


You can check if a database exist by listing all databases in your system by using the "SHOW
DATABASES" statement:

Example

Return a list of your system's databases:

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

Try connecting to the database "mydatabase":

import mysql.connector

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

If the database does not exist, you will get an error.

Creating a Table
To create a table in MySQL, use the "CREATE TABLE" statement.

3|P ag e PREPARED BY :- RADADIYA JITENDRA


BCA SEM – 5 UNIT : - 5

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="yourusername",
password="yourpassword",
database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")

If the above code was executed with no errors, you have now successfully created a table.

Check if Table Exists


You can check if a table exist by listing all tables in your database with the "SHOW TABLES"
statement:

Example

Return a list of your system's databases:

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)

4|P ag e PREPARED BY :- RADADIYA JITENDRA


BCA SEM – 5 UNIT : - 5

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.

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

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 the table already exists, use the ALTER TABLE keyword:

Insert Into Table


To fill a table in MySQL, use the "INSERT INTO" statement.

Example

Insert a record in the "customers" table:

import mysql.connector

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

5|P ag e PREPARED BY :- RADADIYA JITENDRA


BCA SEM – 5 UNIT : - 5

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.")

Important!: Notice the statement: mydb.commit(). It is required to make the changes, otherwise
no changes are made to the table.

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:

Example

Fill the "customers" table with data:

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'),

6|P ag e PREPARED BY :- RADADIYA JITENDRA


BCA SEM – 5 UNIT : - 5

('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.")

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

Insert one row, and return the ID:

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 = ("Michelle", "Blue Village")
mycursor.execute(sql, val)

mydb.commit()

print("1 record inserted, ID:", mycursor.lastrowid)

7|P ag e PREPARED BY :- RADADIYA JITENDRA


BCA SEM – 5 UNIT : - 5

Select From a Table


To select from a table in MySQL, use the "SELECT" statement:

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

mycursor.execute("SELECT * FROM customers")

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

Select only the name and address columns:

import mysql.connector

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

8|P ag e PREPARED BY :- RADADIYA JITENDRA


BCA SEM – 5 UNIT : - 5

mycursor = mydb.cursor()

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

myresult = mycursor.fetchall()

for x in myresult:
print(x)

Using the fetchone() Method


If you are only interested in one row, you can use the fetchone() method.

The fetchone() method will return the first row of the result:

Example

Fetch only one row:

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.fetchone()

print(myresult)

Select With a Filter


When selecting records from a table, you can filter the selection by using the "WHERE"
statement:

Example

Select record(s) where the address is "Park Lane 38": result:

9|P ag e PREPARED BY :- RADADIYA JITENDRA


BCA SEM – 5 UNIT : - 5

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)

Wildcard Characters
You can also select the records that starts, includes, or ends with a given letter or phrase.

Use the % to represent wildcard characters:

Example

Select records where the address contains the word "way":

import mysql.connector

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

mycursor = mydb.cursor()

sql = "SELECT * FROM customers WHERE address LIKE '%way%'"

mycursor.execute(sql)

myresult = mycursor.fetchall()

10 | P a g e PREPARED BY :- RADADIYA JITENDRA


BCA SEM – 5 UNIT : - 5

for x in myresult:
print(x)

Prevent SQL Injection


When query values are provided by the user, you should escape the values.

This is to prevent SQL injections, which is a common web hacking technique to destroy or
misuse your database.

The mysql.connector module has methods to escape query values:

Example

Escape query values by using the placholder %s method:

import mysql.connector

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

mycursor = mydb.cursor()

sql = "SELECT * FROM customers WHERE address = %s"


adr = ("Yellow Garden 2", )

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

Delete any record where the address is "Mountain 21":

11 | P a g e PREPARED BY :- RADADIYA JITENDRA


BCA SEM – 5 UNIT : - 5

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")

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!

Prevent SQL Injection


It is considered a good practice to escape the values of any query, also in delete statements.

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

Escape values by using the placeholder %s method:

import mysql.connector

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

12 | P a g e PREPARED BY :- RADADIYA JITENDRA


BCA SEM – 5 UNIT : - 5

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")

Update Table
You can update existing records in a table by using the "UPDATE" statement:

Example

Overwrite the address column from "Valley 345" to "Canyoun 123":

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")

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!

13 | P a g e PREPARED BY :- RADADIYA JITENDRA


BCA SEM – 5 UNIT : - 5

Prevent SQL Injection


It is considered a good practice to escape the values of any query, also in update statements.

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

Escape values by using the placholder %s method:

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")

14 | P a g e PREPARED BY :- RADADIYA JITENDRA


BCA SEM – 5 UNIT : - 5

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.

There are different types of MySQL joins:

 MySQL INNER JOIN (or sometimes called simple join)


 MySQL LEFT OUTER JOIN (or sometimes called LEFT JOIN)
 MySQL RIGHT OUTER JOIN (or sometimes called RIGHT JOIN)

So let's discuss MySQL JOIN syntax, look at visual illustrations of MySQL JOINS, and explore
MySQL JOIN examples.

INNER JOIN (simple join)


Chances are, you've already written a statement that uses a MySQL INNER JOIN. It is the most
common type of join. MySQL INNER JOINS return all rows from multiple tables where the join
condition is met.

Syntax

The syntax for the INNER JOIN in MySQL is:

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:

15 | P a g e PREPARED BY :- RADADIYA JITENDRA


BCA SEM – 5 UNIT : - 5

The MySQL INNER JOIN would return the records where table1 and table2 intersect.

Example

Here is an example of a MySQL INNER JOIN:

SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date


FROM suppliers
INNER JOIN orders
ON suppliers.supplier_id = orders.supplier_id;

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:

order_id supplier_id order_date


500125 10000 2013/05/12
500126 10001 2013/05/13
500127 10004 2013/05/14

If we run the MySQL SELECT statement (that contains an INNER JOIN) below:

16 | P a g e PREPARED BY :- RADADIYA JITENDRA


BCA SEM – 5 UNIT : - 5

SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date


FROM suppliers
INNER JOIN orders
ON suppliers.supplier_id = orders.supplier_id;

Our result set would look like this:

supplier_id name order_date


10000 IBM 2013/05/12
10001 Hewlett Packard 2013/05/13

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):

SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date


FROM suppliers, orders
WHERE suppliers.supplier_id = orders.supplier_id;

LEFT OUTER JOIN


Another type of join is called a MySQL LEFT OUTER JOIN. This type of join returns all rows
from the LEFT-hand table specified in the ON condition and only those rows from the other
table where the joined fields are equal (join condition is met).

Syntax

The syntax for the LEFT OUTER JOIN in MySQL is:

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:

17 | P a g e PREPARED BY :- RADADIYA JITENDRA


BCA SEM – 5 UNIT : - 5

The MySQL LEFT OUTER JOIN would return the all records from table1 and only those
records from table2 that intersect with table1.

Example

Here is an example of a MySQL LEFT OUTER JOIN:

SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date


FROM suppliers
LEFT JOIN orders
ON suppliers.supplier_id = orders.supplier_id;

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:

order_id supplier_id order_date


500125 10000 2013/05/12
500126 10001 2013/05/13

18 | P a g e PREPARED BY :- RADADIYA JITENDRA


BCA SEM – 5 UNIT : - 5

If we run the SELECT statement (that contains a LEFT OUTER JOIN) below:

SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date


FROM suppliers
LEFT JOIN orders
ON suppliers.supplier_id = orders.supplier_id;

Our result set would look like this:

supplier_id supplier_name order_date


10000 IBM 2013/05/12
10001 Hewlett Packard 2013/05/13
10002 Microsoft <null>
10003 NVIDIA <null>

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.

RIGHT OUTER JOIN


Another type of join is called a MySQL RIGHT OUTER JOIN. This type of join returns all rows
from the RIGHT-hand table specified in the ON condition and only those rows from the other
table where the joined fields are equal (join condition is met).

Syntax

The syntax for the RIGHT OUTER JOIN in MySQL is:

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:

19 | P a g e PREPARED BY :- RADADIYA JITENDRA


BCA SEM – 5 UNIT : - 5

The MySQL RIGHT OUTER JOIN would return the all records from table2 and only those
records from table1 that intersect with table2.

Example

Here is an example of a MySQL RIGHT OUTER JOIN:

SELECT orders.order_id, orders.order_date, suppliers.supplier_name


FROM suppliers
RIGHT JOIN orders
ON suppliers.supplier_id = orders.supplier_id;

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:

order_id supplier_id order_date


500125 10000 2013/08/12
500126 10001 2013/08/13
500127 10002 2013/08/14

If we run the SELECT statement (that contains a RIGHT OUTER JOIN) below:

20 | P a g e PREPARED BY :- RADADIYA JITENDRA


BCA SEM – 5 UNIT : - 5

SELECT orders.order_id, orders.order_date, suppliers.supplier_name


FROM suppliers
RIGHT JOIN orders
ON suppliers.supplier_id = orders.supplier_id;

Our result set would look like this:

order_id order_date supplier_name


500125 2013/08/12 Apple
500126 2013/08/13 Google
500127 2013/08/14 <null>

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.

21 | P a g e PREPARED BY :- RADADIYA JITENDRA

You might also like