Python
Python
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Unit-V
Database
Programming
IV B.TECH CSE
Environment Setup
• To build the real world applications,
connecting with the databases is the
necessity for the programming languages.
However, python allows us to connect our
application to the databases like MySQL,
SQLite, MongoDB, and many others.
• we will discuss Python - MySQL connectivity
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
• We need to install it to get it working.
• Execute the following command to install it
using pip installer.
Database Connection
There are the following steps to connect a
python application to our database.
• Import mysql.connector module
• Create the connection object.
• Create the cursor object
• Execute the query
Creating the connection
• To create a connection between the MySQL
database and the python application, the
connect() method of mysql.connector
module is used.
• Pass the database details like HostName,
username, and the database password in
the method call. The method returns the
connection object.
• Connection-
Object= mysql.connector.connect(host = <ho
st-
name> , user = <username> , password = <p
assword> )
Example:
• import mysql.connector
#Create the connection object
• myconn = mysql.connector.connect(host = "l
ocalhost", user = "root",password = "google")
Output:
<mysql.connector.connection.MySQLConnec
tion object at 0x7fb142edd780>
Connect to a database
• import mysql.connector
• #Create the connection object
• myconn = mysql.connector.connect(host = "localhost", u
ser = "root",password = "google", database = "mydb")
• #printing the connection object
• print(myconn)
Output:
• <mysql.connector.connection.MySQLConnection
object at 0x7ff64aa3d7b8>
What is Cursor
• To execute SQL statements, a work area is used
by DBMS engine for its internal processing and
storing the information.
• The major function of a cursor is to retrieve data,
one row at a time, from a result set
Creating a cursor object
• The cursor object can be defined as an
abstraction specified in the Python DB-API.
It facilitates us to have multiple separate
working environments through the same
connection to the database.
• We can create the cursor object by calling
the 'cursor' function of the connection
object.
• The cursor object is an important aspect of
executing queries to the databases.
• The syntax to create the cursor object is
given below.
• <my_cur> = conn.cursor()
Example
• import mysql.connector
#Create the connection object
• myconn = mysql.connector.connect(host = "l
ocalhost", user = "root",passwd = "google", d
atabase = "mydb")
• #printing the connection object
• print(myconn) Output:
<mysql.connector.conne
#creating the cursor object ction.MySQLConnection
object at
• cur = myconn.cursor() 0x7faa17a15748>
• print(cur) MySQLCursor: (Nothing
executed yet)
Show databases
• Getting the list of existing databases
• We can get the list of all the databases by
using the following MySQL query.
• > show databases;
Example
• import mysql.connector
• #Create the connection object
• myconn = mysql.connector.connect(host = "l
ocalhost", user = "root",passwd = "google")
• #creating the cursor object
• cur = myconn.cursor()
• dbs = cur.execute("show databases")
•
Output:
• for x in cur:
• print(x) All Created Databases
names are displayed
• myconn.close()
Creating the new database
• import mysql.connector
• #Create the connection object
• myconn = mysql.connector.connect(host = "l
ocalhost", user = "root",passwd = "google")
• #creating the cursor object
• cur = myconn.cursor()
• #creating a new database
cur.execute("create database PythonDB2")
• for x in cur:
• print(x)
• myconn.close()
Creating the table
• We have to mention the database name
while establishing the connection object.
• We can create the new table by using the
CREATE TABLE statement of SQL. In our
database PythonDB, the table Employee will
have the four columns, i.e., name, id, salary,
and department_id initially.
• The following query is used to create the
new table Employee.
• > create table Employee (name varchar(20) not
null, id int primary key, salary float not null, Dept_
Id int not null)
Example to create a table
• import mysql.connector
• #Create the connection object
• myconn = mysql.connector.connect(host = "localhost"
, user = "root",passwd = "google",database = "PythonD
B")
• #creating the cursor object
• cur = myconn.cursor()
• #Creating a table with name Employee having four co
lumns i.e., name, id, salary, and department id
• dbs = cur.execute("create table Employee(name varch
ar(20) not null, id int(20) not null primary key, salary
float not null, Dept_id int not null)")
• myconn.close()
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
• #Create the connection object
• myconn = mysql.connector.connect(host = "l
ocalhost", user = "root",password = "google",
database = "PythonDB")
• #creating the cursor object
• cur = myconn.cursor()
• #adding a column branch name to the table
Employee
• cur.execute("alter table Employee add branc
h_name varchar(20) not null")
• myconn.close()
Output in MySQL
Insert Operation
• The INSERT INTO statement is used to add
a record to the table. In python, we can
mention the format specifier (%s) in place of
values.
• We provide the actual values in the form of
tuple in the execute() method of the cursor.
Example
• import mysql.connector
• myconn = mysql.connector.connect(host = "localh
ost", user = "root",passwd = "google",database = "P
ythonDB")
• cur = myconn.cursor()
• sql = "insert into Employee(name, id, salary, dept_
id, branch_name) values (%s, %s, %s, %s, %s)"
• #The row values are provided in the form of tuple
val = ("John", 110, 25000.00, 201, "Newyork")
• cur.execute(sql,val) Output:
Output:
3 records inserted!
Output in MySQL
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 = "l
ocalhost", user = "root",passwd = "google",da
tabase = "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")
Example Cont..
• #inserting the values into the table
• cur.execute(sql,val)
•
Output:
• #commit the transaction 1 record inserted! Id: 0
• myconn.commit()
•
• #getting rowid
• print(cur.rowcount,"record inserted! id:",
cur.lastrowid)
myconn.close()
Read Operation
• 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
• #Create the connection object
• myconn = mysql.connector.connect(host = "localhost"
, user = "root",passwd = "google",database = "Python
DB")
• #creating the cursor object
• cur = myconn.cursor()
• #Reading the Employee data
• cur.execute("select * from Employee")
• #fetching the rows from the cursor object
• result = cur.fetchall()
Example Cont..
• #printing the result
• for x in result:
• print(x);
• myconn.close()
Output:
Output:
('John', 101, 25000.0)
Object-relational
Managers (ORM)
Object-relational Mapping
• An object-relational mapper (ORM) is a code
library that automates the transfer of data
stored in relational database tables into
objects that are more commonly used in
application code.
What is ORM?
• ORM (Object Relational Mapping) is a
programming technique for converting data
between incompatible type systems in
object-oriented programming languages.
Usually, the type system used in an Object
Oriented (OO) language like Python contains
non-scalar types. These cannot be
expressed as primitive types such as
integers and strings.
• Hence, the OO programmer has to convert
objects in scalar data to interact with
backend database. However, data types in
most of the database products such as
Oracle, MySQL, etc., are primary.
What is ORM? Cont..
• In an ORM system, each class maps to a
table in the underlying database. Instead of
writing tedious database interfacing code
yourself, an ORM takes care of these issues
for you while you can focus on programming
the logics of the system.
• ORMs can be thought of as a translator
converting our code from one form to
another.
What is ORM? Cont..
• The ORM software generates objects (as in
OOP) that virtually map (like the map of a
city) the tables in your database. Then the
programmer would use these objects to
interact and play with the database! So the
core idea is to try and shield the
programmer from having to write optimized
and complex SQL code — the ORM
generated objects take care of that for you.
• Say for example you had a database table
and are developing an application in python
this is how your flow would look like:
What is ORM? Cont..
• Object-relational mapping refers to
synchronization between two different
representations of data. From one side,
there is a relational database, where the
data is represented in terms of tuples,
grouped into relations, while in application
we manipulate objects.
What is ORM? Cont..
Advantages of ORM
• They write correct and optimized SQL
queries, thereby eliminating the hassle for
developers
• They make the code easier to update,
maintain, and reuse as the developer can
think of, and manipulate data as objects
• ORMs will shield your application from SQL
injection attacks since the framework will
filter the data for you!
• ORMs provide the concept of Database
Abstraction which makes switching
databases easier and creates a consistent
code base for your application.
Why are ORMs useful?
• ORMs provide a high-level abstraction upon
a relational database that allows a developer
to write Python code instead of SQL to
create, read, update and delete data and
schemas in their database. Developers can
use the programming language they are
comfortable with to work with a database
instead of writing SQL statements or stored
procedures.
Why are ORMs useful?
• For example, without an ORM a developer
would write the following SQL statement to
retrieve every row in the USERS table where
the zip_code column is 94107:
• SELECT * FROM USERS WHERE
zip_code=94107;
• The equivalent Django ORM query would
instead look like the following Python code:
• # obtain everyone in the 94107 zip code and
assign to users variable users =
Users.objects.filter(zip_code=94107)
Why are ORMs useful?
• The ability to write Python code instead of
SQL can speed up web application
development, especially at the beginning of
a project. The potential development speed
boost comes from not having to switch from
Python code into writing declarative
paradigm SQL statements. While some
software developers may not mind switching
back and forth between languages, it's
typically easier to knock out a prototype or
start a web application using a single
programming language.
Do I have to use an ORM for my web application?