CH - 4 Advance Python
CH - 4 Advance Python
Sem - 6
1. Configuring database
2. Defining model
3. Basic data access
4. Inserting and updating data
5. Selecting objects
6. Deleting objects
Install mysql.connector:
To connect the python application with the MySQL database, we must import the
mysql.connector module in the program.
The mysql.connector is not a built-in module that comes with the python installation. We
need to install it to get it working.
Execute the following command to install it using pip installer.
> python -m pip install mysql-connector
Page 1 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
This will take a bit of time to install mysql-connector for python. We can verify the
installation once the process gets over by importing mysql-connector on the python shell.
Database Connection:
We will discuss the steps to connect the python application to the database.
There are the following steps to connect a python application to our database.
1. Import mysql.connector module
2. Create the connection object.
3. Create the cursor object
4. Execute the query
Syntax:
ConnectionObject= mysql.connector.connect(host = <hostname> , user = <username> ,
passwd =<password> )
Example:
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "")
Page 2 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
Here, we must notice that we can specify the database name in the connect() method if
we want to connect to a specific database.
Example:
import mysql.connector
Output:
<mysql.connector.connection.MySQLConnection object at 0x7ff64aa3d7b8>
print(cur)
Page 3 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
Output:
<mysql.connector.connection.MySQLConnection object at 0x7faa17a15748>
MySQLCursor: (Nothing executed yet)
Example:
import mysql.connector
try:
dbs = cur.execute("show databases")
except:
myconn.rollback()
for x in cur:
print(x)
myconn.close()
Output:
('EmployeeDB',)
('Test',)
('TestDB',)
('information_schema',)
('javatpoint',)
('javatpoint1',)
('mydb',)
('mysql',)
('performance_schema',)
('testDB',)
Page 4 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
Example:
import mysql.connector
try:
#creating a new database
cur.execute("create database PythonDB2")
#getting the list of all the databases which will now include the new database PythonDB
except:
myconn.rollback()
for x in cur:
print(x)
myconn.close()
Output:
('EmployeeDB',)
('PythonDB',)
('Test',)
('TestDB',)
('anshika',)
('information_schema',)
('javatpoint',)
('javatpoint1',)
('mydb',)
('mydb1',)
('mysql',)
Page 5 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
('performance_schema',)
('testDB',)
Example:
import mysql.connector
try:
#Creating a table with name Employee having four columns i.e., name, id, salary, and de
partment id
dbs = cur.execute("create table Employee(name varchar(20) not null, id int(20) not null
primary key, salary float not null, Dept_id int not null)")
except:
myconn.rollback()
myconn.close()
Page 6 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
Now, we may check that the table Employee is present in the database.
4. Alter Table:
Sometimes, we may forget to create some columns, or we may need to update the table
schema.
The alter statement used to alter the table schema if required.
Here, we will add the column branch_name to the table Employee.
The following SQL query is used for this purpose.
>alter table Employee add branch_name varchar(20) not null
Example:
import mysql.connector
Page 7 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
cur = myconn.cursor()
try:
#adding a column branch name to the table Employee
cur.execute("alter table Employee add branch_name varchar(20) not null")
except:
myconn.rollback()
myconn.close()
Page 8 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
Example:
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "",
database = "PythonDB")
#creating the cursor object
cur = myconn.cursor()
sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %
s, %s)"
try:
#inserting the values into the table
cur.execute(sql,val)
except:
myconn.rollback()
print(cur.rowcount,"record inserted!")
myconn.close()
Output:
1 record inserted!
Page 9 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
Example:
import mysql.connector
Page 10 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
try:
#inserting the values into the table
cur.executemany(sql,val)
except:
myconn.rollback()
myconn.close()
Output:
3 records inserted!
Page 11 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
Row ID:
In SQL, a particular row is represented by an insertion id which is known as row id.
We can get the last inserted row id by using the attribute lastrowid of the cursor object.
Example:
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",dat
abase = "PythonDB")
#creating the cursor object
cur = myconn.cursor()
sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %
s, %s)"
val = ("Mike",105,28000,202,"Guyana")
try:
#inserting the values into the table
cur.execute(sql,val)
#getting rowid
print(cur.rowcount,"record inserted! id:",cur.lastrowid)
except:
myconn.rollback()
myconn.close()
Output:
1 record inserted! Id: 0
2. Update Operation:
The UPDATE-SET statement is used to update any column inside the table.
The following SQL query is used to update a column.
> update Employee set name = 'alex' where id = 110
Page 12 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
Example:
import mysql.connector
try:
#updating the name of the employee whose id is 110
cur.execute("update Employee set name = 'alex' where id = 110")
myconn.commit()
except:
myconn.rollback()
myconn.close()
Page 13 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
Selecting objects:
The SELECT statement is used to read the values from the databases.
We can restrict the output of a select query by using various clause in SQL like where,
limit, etc.
Python provides the fetchall() method returns the data stored inside the table in the form
of rows.
We can iterate the result to get the individual rows.
We will extract the data from the database by using the python script.
We will also format the output to print it on the console.
Example:
import mysql.connector
try:
#Reading the Employee data
cur.execute("select * from Employee")
for x in result:
print(x);
except:
myconn.rollback()
myconn.close()
Output:
('John', 101, 25000.0, 201, 'Newyork')
('John', 102, 25000.0, 201, 'Newyork')
('David', 103, 25000.0, 202, 'Port of spain')
('Nick', 104, 90000.0, 201, 'Newyork')
('Mike', 105, 28000.0, 202, 'Guyana')
Page 14 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
Example:
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "",
database = "PythonDB")
#creating the cursor object
cur = myconn.cursor()
try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee")
Output:
('John', 101, 25000.0)
('John', 102, 25000.0)
('David', 103, 25000.0)
('Nick', 104, 90000.0)
('Mike', 105, 28000.0)
Page 15 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
Example:
import mysql.connector
try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee")
except:
myconn.rollback()
myconn.close()
Output:
('John', 101, 25000.0)
Page 16 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
cur = myconn.cursor()
try:
print("Name id Salary");
for row in result:
print("%s %d %d"%(row[0],row[1],row[2]))
except:
myconn.rollback()
myconn.close()
Output:
Name id Salary
John 101 25000
John 102 25000
David 103 25000
Nick 104 90000
Mike 105 28000
try:
#Reading the Employee data
Page 17 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
cur.execute("select name, id, salary from Employee where name like 'J%'")
print("Name id Salary");
myconn.close()
Output:
Name id Salary
John 101 25000
John 102 25000
try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee where id in (101,102,103)")
print("Name id Salary");
Page 18 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
myconn.rollback()
myconn.close()
Output:
Name id Salary
John 101 25000
John 102 25000
David 103 2500
Example:
import mysql.connector
try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee order by name")
print("Name id Salary");
myconn.close()
Output:
Name id Salary
Page 19 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
Order by DESC:
This orders the result in the decreasing order of a particular column.
Example:
import mysql.connector
try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee order by name desc")
except:
myconn.rollback()
myconn.close()
Page 20 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
Output:
Name id Salary
Nick 104 90000
Mike 105 28000
John 101 25000
John 102 25000
David 103 25000
Deleting objects:
The DELETE FROM statement is used to delete a specific record from the table.
Here, we must impose a condition using WHERE clause otherwise all the records from
the table will be removed.
The following SQL query is used to delete the employee detail whose id is 110 from the
table.
> delete from Employee where id = 110
Example
import mysql.connector
try:
#Deleting the employee details whose id is 110
cur.execute("delete from Employee where id = 110")
myconn.commit()
except:
myconn.rollback()
myconn.close()
Performing Transactions:
Transactions ensure the data consistency of the database.
We have to make sure that more than one applications must not modify the records while
performing the database operations.
The transactions have the following properties.
Page 21 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
1. Atomicity:
Either the transaction completes, or nothing happens. If a transaction contains 4 queries
then all these queries must be executed, or none of them must be executed.
2. Consistency:
The database must be consistent before the transaction starts and the database must also
be consistent after the transaction is completed.
3. Isolation:
Intermediate results of a transaction are not visible outside the current transaction.
4. Durability:
Once a transaction was committed, the effects are persistent, even after a system failure.
Example:
import mysql.connector
Page 22 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
try:
cur.execute("delete from Employee where Dept_id = 201")
myconn.commit()
print("Deleted !")
except:
print("Can't delete !")
myconn.rollback()
myconn.close()
Output:
Deleted !
Page 23 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
A database can contain multiple collections, but a collection cannot span multiple
databases.
Likewise, a collection can contain multiple documents, but a document cannot span
multiple collections.
MongoDB is a cross-platform, document oriented database that provides, high
performance, high availability, and easy scalability.
MongoDB works on concept of collection and document.
1. Database:
Database is a physical container for collections.
Each database gets its own set of files on the file system.
A single MongoDB server typically has multiple databases.
2. Collection:
Collection is a group of MongoDB documents.
It is the equivalent of an RDBMS table.
A collection exists within a single database.
Collections do not enforce a schema.
Documents within a collection can have different fields.
Typically, all documents in a collection are of similar or related purpose.
3. Document:
A document is a set of key-value pairs.
Documents have dynamic schema.
Dynamic schema means that documents in the same collection do not need to have the
same set of fields or structure, and common fields in a collection's documents may hold
different types of data.
The following table shows the relationship of RDBMS terminology with MongoDB.
RDBMS MongoDB
Database Database
Table Collection
Tuple/Row Document
column Field
Table Join Embedded Documents
Primary Key Primary Key (Default key _id provided
by MongoDB itself)
Database Server and Client
mysqld/Oracle mongod
mysql/sqlplus mongo
Page 24 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
Any relational database has a typical schema design that shows number of tables and the
relationship between these tables.
While in MongoDB, there is no concept of relationship.
Page 25 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-
32\Scripts>python –m pip install pymongo
Now you have downloaded and installed a mongoDB driver.
Test PyMongo:
To test if the installation was successful, or if you already have "pymongo" installed,
create a Python page with the following content:
demo_mongodb_test.py:
import pymongo
If the above code was executed with no errors, "pymongo" is installed and ready to be
used.
Defining model:
Data in MongoDB has a flexible schema.documents in the same collection.
They do not need to have the same set of fields or structure Common fields in a
collection’s documents may hold different types of data.
Data Model Design
MongoDB provides two types of data models: — Embedded data model and Normalized
data model. Based on the requirement, you can use either of the models while preparing
your document.
1. Embedded Data Model:
In this model, you can have (embed) all the related data in a single document, it is also
known as de-normalized data model.
For example, assume we are getting the details of employees in three different documents
namely, Personal_details, Contact and, Address, you can embed all the three documents
in a single one as shown below −
{
_id: ,
Emp_ID: "10025AE336"
Personal_details:{
First_Name: "Radhika",
Last_Name: "Sharma",
Date_Of_Birth: "1995-09-26"
},
Contact: {
e-mail: "[email protected]",
phone: "9848022338"
},
Address: {
city: "Hyderabad",
Area: "Madapur",
State: "Telangana"
}
Page 26 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
}
2. Normalized Data Model
In this model, you can refer the sub documents in the original document, using
references. For example, you can re-write the above document in the normalized model
as:
Employee:
{
_id: <ObjectId101>,
Emp_ID: "10025AE336"
}
Personal_details:
{
_id: <ObjectId102>,
empDocID: " ObjectId101",
First_Name: "Radhika",
Last_Name: "Sharma",
Date_Of_Birth: "1995-09-26"
}
Contact:
{
_id: <ObjectId103>,
empDocID: " ObjectId101",
e-mail: "[email protected]",
phone: "9848022338"
}
Address:
{
_id: <ObjectId104>,
empDocID: " ObjectId101",
city: "Hyderabad",
Area: "Madapur",
State: "Telangana"
}
Page 27 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
Creating a Database
To create a database in MongoDB, start by creating a MongoClient object, then specify a
connection URL with the correct ip address and the name of the database you want to
create.
MongoDB will create the database if it does not exist, and make a connection to it.
Example:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
Example:
print(myclient.list_database_names())
Example:
Page 28 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
Creating a Collection:
A collection in MongoDB is the same as a table in SQL databases.
To create a collection in MongoDB, use database object and specify the name of the
collection you want to create.
MongoDB will create the collection if it does not exist.
Example:
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
print(mydb.list_collection_names())
Example:
Page 29 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
Example:
x = mycol.insert_one(mydict)
Example:
Insert another record in the "customers" collection, and return the value of
the _id field:
mydict = { "name": "Peter", "address": "Lowstreet 27" }
x = mycol.insert_one(mydict)
print(x.inserted_id)
If you do not specify an _id field, then MongoDB will add one for you and assign a
unique id for each document.
In the example above no _id field was specified, so MongoDB assigned a unique _id for
the record (document).
Page 30 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
Example:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mylist = [
{ "name": "Amy", "address": "Apple st 652"},
{ "name": "Hannah", "address": "Mountain 21"},
{ "name": "Michael", "address": "Valley 345"},
{ "name": "Sandy", "address": "Ocean blvd 2"},
{ "name": "Betty", "address": "Green Grass 1"},
{ "name": "Richard", "address": "Sky st 331"},
{ "name": "Susan", "address": "One way 98"},
{ "name": "Vicky", "address": "Yellow Garden 2"},
{ "name": "Ben", "address": "Park Lane 38"},
{ "name": "William", "address": "Central st 954"},
{ "name": "Chuck", "address": "Main Road 989"},
{ "name": "Viola", "address": "Sideway 1633"}
]
x = mycol.insert_many(mylist)
Example:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mylist = [
Page 31 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
x = mycol.insert_many(mylist)
Update Collection:
You can update a record, or document as it is called in MongoDB, by using
the update_one() method.
The first parameter of the update_one() method is a query object defining which
document to update.
Note: If the query finds more than one record, only the first occurrence is updated.
The second parameter is an object defining the new values of the document.
Page 32 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
Example:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mycol.update_one(myquery, newvalues)
Update Many:
To update all documents that meets the criteria of the query, use
the update_many() method.
Example:
Update all documents where the address starts with the letter "S":
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
x = mycol.update_many(myquery, newvalues)
Page 33 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
Selecting objects:
Find One:
To select data from a collection in MongoDB, we can use the find_one() method.
The find_one() method returns the first occurrence in the selection.
Example:
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
x = mycol.find_one()
print(x)
Find All:
To select data from a table in MongoDB, we can also use the find() method.
The find() method returns all occurrences in the selection.
The first parameter of the find() method is a query object.
In this example we use an empty query object, which selects all documents in the
collection.
No parameters in the find() method gives you the same result as SELECT * in MySQL.
Example:
Return all documents in the "customers" collection, and print each document:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
for x in mycol.find():
print(x)
Page 34 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
Example:
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
Example:
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
Example:
You get an error if you specify both 0 and 1 values in the same object (except if one of the
fields is the _id field):
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
Page 35 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
Example:
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mydoc = mycol.find(myquery)
for x in mydoc:
print(x)
Advanced Query:
To make advanced queries you can use modifiers as values in the query object.
E.g. to find the documents where the "address" field starts with the letter "S" or higher
(alphabetically), use the greater than modifier: {"$gt": "S"}:
Example:
Find documents where the address starts with the letter "S" or higher:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
Page 36 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
mydoc = mycol.find(myquery)
for x in mydoc:
print(x)
Example:
Find documents where the address starts with the letter "S":
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mydoc = mycol.find(myquery)
for x in mydoc:
print(x)
Example:
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
Page 37 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
mydoc = mycol.find().sort("name")
for x in mydoc:
print(x)
Sort Descending:
Use the value -1 as the second parameter to sort descending.
sort("name", 1) #ascending
sort("name", -1) #descending
Example:
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
for x in mydoc:
print(x)
Deleting objects:
Delete Document:
To delete one document, we use the delete_one() method.
The first parameter of the delete_one() method is a query object defining which
document to delete.
Note: If the query finds more than one document, only the first occurrence is deleted.
Example:
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
Page 38 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mycol.delete_one(myquery)
Example:
Delete all documents were the address starts with the letter S:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
Example:
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
x = mycol.delete_many({})
Page 39 of 40
Subject: ADVANCE PYTHON Chapter - 4 B.C.A. Sem - 6
Example
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mycol.drop()
The drop() method returns true if the collection was dropped successfully, and false if the
collection does not exist.
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
myresult = mycol.find().limit(5)
Page 40 of 40