You are on page 1of 40

Free

Full Syllabus Notes with Video Explanations


For
Term 2 Examination
Class 12 Computer Science (CBSE)

If you want to give some donation then


My QR Code:

And UPI ID:


govind10788@okicici
Chapter 6: Data Structures in Python For Video Lecture Click here:

What is Data Structure:


Data structure is a way of storing, organizing and fetching data in computer.

What is Stack:
A stack is a linear data structure in python in which addition and deletion of elements can be done at one
end only that is called TOP. A stack is known as LIFO (Last – In, First – Out) data structure in python.
Insertion in stack is also known as a PUSH operation. Deletion from stack is also known as POP operation
in stack.

Working with Stack using List / Implementation of Stack using List:


Working with stack is similar to working with list. Basic operations that we should know are :
1. How to create an empty stack?
2. How to add elements to a stack?
3. How to delete / remove elements from the stack
4. How to traverse or displaying elements of stack?
5. How to check for empty stack?

Create an empty stack:


st = [ ] or st = list( )

Adding an element to a Stack : This is known as PUSH


st.append(5)

Deleting / removing elements from the stack : This is known as POP


st.pop( )

Traverse or displaying elements of stack:

L = len(st)
for i in range(L-1, -1, -1) : #to display in reverse order
print(st[i])

Check for empty stack (is_empty):


if (st == [ ]):
print("stack is empty")

Overflow and Underflow:


Overflow: It refers to a situation, when one tries to push an element in stack/queue, that is full. In python
list OVERFLOW condition does not arise until all memory is exhausted because list can grow as per data.

Underflow: It refers to situation when one tries to pop/delete an item from an empty stack or queue.
Example:
List=[]
List.pop()

What is Queue:

Queue is a data structures that is based on First In First Out (FIFO) strategy. Elements are added at one end
called Rear and removed from other end called Front. In a queue, one end is always used to insert data
(enqueue) and the other is used to delete data (dequeue), because queue is open at both its ends.

Operations on Queue:
Enqueue: In this a new element is added at the end of list called Rear.
Dequeue: In this an element is to be deleted from one end called Front.
Is empty: It is used to check whether the queue has any element or not. It is used to avoid underflow
condition while performing Dequeue operation.
Is full: It is used to check whether any more elements can be added to the queue or not, to avoid the
overflow condition while performing Enqueue operation.
Peek: It is used to view element at the front and back of the queue, without removing it from the queue.
We can do this by: list[0] or list[-1]
Working with Queue using List / Implementation of Queue using List:
Basic operations that we should know are :
1. How to create an empty Queue?
2. How to add elements to a Queue?
3. How to delete / remove elements from the Queue?
4. How to traverse or displaying elements of Queue?
5. How to check for empty Queue?

Create an empty Queue:


st = [ ] or st = list( )

Adding an element to a Queue : This is known as Enqueue


st.append(5)

Deleting / removing elements from the Queue : This is known as Dequeue


st.pop(0)

Traverse or displaying elements of Queue:


L = len(st)
for i in range(0, L,) :
print(st[i])

Check for empty Queue (is_empty):


if (st == [ ]):
print("Queue is empty")

Difference between Stack and Queue:

Stack Queue
Stack is a data structures that is based on Last In Queue is a data structures that is based on First In
First Out (LIFO) strategy. First Out (FIFO) strategy.
Insertion and deletion of elements can be done at Elements are added at one end called Rear and
one end only that id called TOP. removed from other end called Front.

Insertion in stack is also known as a PUSH Insertion in Queue is also known as a Enqueue
operation. Deletion from stack is also known as POP operation. Deletion from Queue is also known as
operation in stack. Dequeue operation in stack.
Important Questions for Exams For Video Lecture Click Here:
Q1. Write a function push(),pop() and display() to add a new student name, remove a student name and
to display student names in stack format, according to Data Structure in Python.
st=[ ]
def push():
sn=input("Enter name of student:")
st.append(sn)
print(st)

def pop():
if st==[]:
print("Stack is empty")
else:
print("Deleted student name :",st.pop())

def display():
if st==[]:
print("Stack is empty")
else:
for i in st[::-1]:
print(i)

Q2. Write a function Push() which to add in a stack named "MyStack". After calling push() three times, a
message should be displayed "Stack is Full"

st=[ ]
StackSize=3
def push():
sn=input("Enter name of student:")
if len(st)<StackSize:
st.append(sn)
else:
print("Stack is full!")
print(st)

Q3: Julie has created a dictionary containing names and marks as key value pairs of 6 students. Write a
program, with separate user defined functions to perform the following operations:
 Push the keys (name of the student) of the dictionary into a stack, where the corresponding
value (marks) is greater than 75.
 Pop and display the content of the stack.

R={"OM":76, "JAI":45, "BOB":89,"ALI":65, "ANU":90, "TOM":82}


st=[]
def push():
for i in R:
if R[i]>75:
st.append(i)
print(st)

def pop():
while True:
if st!=[]:
print(st.pop(),end=" ")
else:
break

Q4: Alam has a list containing 10 integers. You need to help him create a program with separate user
defined functions to perform the following operations based on this list.
 Traverse the content of the list and push the even numbers into a stack.
 Pop and display the content of the stack.

N=[12, 13, 34, 56, 21, 79, 98, 22, 35, 38]
st=[]
def push():
for i in N:
if i%2==0:
st.append(i)

def pop():
while True:
if st!=[]:
print(st.pop(),end=" ")
else:
break

Q 5: Write a function push(l) to perform push opration in stack. Where a list is given:
L=[10,12,15,16,17,18,20,21,25]
Push only those element who is divisible by 5.

def push(l):
L2.append(l)

L2=[]
L1=[10,12,15,16,17,18,20,21,25]
for i in L1:
if i%5==0:
push(i)
print("Original List:\n",L1)
print("List after using push:\n",L2)

Q 6: Write a function Addvowel(l) to perform push opration in stack. Where a list is given:
L=[‘Ansh’,’Vipin’,’Ishan’,’Devesh’,’Om’,’Upashna’]
Push only those element who is started from vowels

def Addvowel(l):
L2.append(l)

L2=[]
L1=['Ansh','Vipin','Ishan','Devesh','Om','Upashna']
for i in L1:
if i[0] in 'aeiouAEIOU':
Addvowel(i)

print("Original List:\n",L1)
print("List after using push:\n",L2)
Chapter 7: Computer Networks (Part 1) For Video Lecture Click Here:
What is Computer Networks:

A computer network is a collection of interconnected computers and other devices to share data and
other resources ( hardware and software resource ) is called computer network.

Advantages of Computer Networks:

 Resource Sharing: It is used to share users programs,


application, data and peripheral devices connected to the
network.
 Improved communication: Its enables fast, reliable and secure
communication between users, other than this whatever the
changes at one end are done can be immediately noticed at
another.
 Reduced communication cost: Using network, we can send
large quantity of data at low cost. Like text, image, audio and
video data.
 Reliability of data: It means backing up of data, data can be copied and stored on multiple computers, So if
due to some reasons data gets corrupted and becomes unavailable on one computer, a copy of the same
data can be accessed from another computer in network.

Disadvantages of Computer Networks:

 Cost of setup and maintenance: It is very costly to set up larger network, cabling and equipment cost can
be expensive and maintenance cost may be very high for large networks.
 Threat to data security: Hacking, data corruption, computer viruses, worms, malware, phishing etc, are
some of the threats to network security.

Evolution of Computer Network:

 ARPANET: It is the first network and came into existence in 1969, The US department of defense formed
an agency named ARPANET (Advanced Research Projects Agency NETwork) to connect computers at
various universities and defense agencies. The main objective of ARPANET was to develop a network that
could continue to function efficiently even in the event of a nuclear attack.
 NSFNET: In mid 80’s another federal agency, NSFNET (National Science Federation Network) created a
new network which was more capable than ARPANET. Its main aim was to use network only for
academic research and not for any kind of private business activity.
 Internet: Later, many privately owned businesses with their very own private systems joined with
ARPANET and NSFNET to make more capable and wide network, the Internet. ARPANET + NSFNET +
PRIVATE NETWORKS = INTERNET. The internet is a globally connected network system that utilizes
TCP/IP to transmit information.
Following services are instantly available through internet : Email, Web-enabled audio/video
conferencing services, Online movies and gaming , Data transfer/file-sharing, Instant messaging , Internet
forums , Social networking , Online shopping ,Financial services.
 Interspace: It is a client/server software program that allows multiple users to communicate online with
real –time audio, video and text chat in dynamic 3D environments.

Data communication terminologies:


What is Communication: Communication means sending or receiving information between different
devices of network.
Components of communications:
1. Sender: A device or a computer that sends
the data.
2. Receiver: A device or a computer that
receives the data.
3. Message/data: This is the information to
be communicated. It may be text, image,
audio or video.
4. Transmission Medium/Channel: A
transmission medium is a physical path
through which the data flows sender to receiver. A cable or wire or radio waves can be the medium.
5. Protocol: It means set of rules for data transmission. It represents the communication methods which are
to be followed by the sending and receiving devices. Such as TCP/IP, http, smtp.

Measuring capacity of communication media:


Bandwidth: The maximum amount of data that can be transferred through communication channel one
point to another. Bandwidth is measured in Hertz.
Data Transfer Rate/Speed: DTR is the amount of data in digital form that is moved from one place to
another in a given time on a network. Data transfer rate is usually measured in bps(bits per second), Kbps(
kilobits per second), Mbps (megabits per second), Gbps giga (bits per second) and Tbps( tera bits per
second).
Switching techniques/ Different ways of sending data across network:
Switching techniques are used for transmitting data across networks. Different ways of sending data across
the network are:
1) Circuit Switching: In Circuit Switching a dedicated path/link
established between sender and receiver. This method of switching is
used in analog telephone lines. It established Physical Connection
between sender and receiver. And mostly used for voice
communication.
2) Packet Switching: In packet switching, the data is break down into
several fragments of same size called packets. Each packet has a source
and destination address. There is no physical connection established
between sender and receiver. It uses TCP/IP protocol.

3) Message Switching: It is a store and forward switching technique where


there is no direct connection between the sender and receiver.

Circuit Switching Vs Packet Switching:

Packet Switching Circuit Switching

No physical Connection between Physical Connection established between


sender and receiver sender and receiver

No dedicated path for packets Dedicated path for packets

Internet Protocol Address or IP Address:


IP (Internet Protocol) Address is an address of your network hardware. It helps in connecting your
computer to other devices on your network and all over the world. An IP Address is made up of some
numbers.
An example of an IP address would be: 506.457.14.512
There are two IP versions:

IPv4 IPv6
IPv4 is a 32 bit address IPv6 is a 128 bit address.
IPv4 is the older version which has an space IPv6 is the new version can provide up to trillions of IP
of over 4 billion IP addresses. addresses.
Example: Example: 2001:0db8:0000:0000:0000:ff00:0042:7879
12.244.233.165
Chapter 7: Computer Networks (Part 2) For Video Lecture Click Here:

Communication Media / Transmission Media:


It is a channel through which data can be
transferred between different devices of network.
Types of communication media:

 Guided media ( Wired Media )


 Unguided media ( Wireless Media )

Guided media ( Wired media)


This media uses wires for transmitting data. Types of
wired connections are Twisted pair wire / Ethernet
cable/Twisted pair cable, Coaxial cable and Fibre
optic cable.
1. Ethernet Cable: It is also known as twisted pair cable.
There are two identical 1mm wires wrapped together and
twisted around each other. The twisted pair cables are
twisted in order to reduce crosstalk and electromagnetic
induction.

Advantages of Ethernet Cable


 It is simple, inexpensive and easy to install and maintain.
 Good for short area networking.

Disadvantages of Ethernet Cable


 Using Ethernet cable, signals cannot be transported over
long distances without using repeaters.
 It is not suitable for broadband applications as it has low
bandwidth capabilities.

Twisted pair comes in two varieties:


 Unshielded twisted pair (UTP)
 Shielded twisted pair (STP)

2. Coaxial cable: It consists of a solid wire core surrounded


by one or more foil or braided wire shields, each part is
separated from the other by some kind of plastic insulator. It
is mostly used in the cable wires.

Advantages of Coaxial cable:

 Data transmission rate is better than Twisted pair cable.


 It provides a cheap means of transporting multi-channel television signals around metropolitan areas.

Disadvantages of Coaxial cable:

 A thick coaxial cable does not bend easily and thus is difficult to install.
 It is expensive as compared to Twisted pair cable.

3. Optical Fibre: An optical fibre consists of thin glass fibres that can carry information in the form of
visible light.

Advantages of Optical Fibre:

 Transmit data over long distance with high security.


 Data transmission speed is very high.
 Provide better noise immunity.
 Bandwidth is up to 10gbps.

Disadvantages of Optical Fibre:

 A highly skilled labor is required for its installation and maintenance.


 It is relatively expensive as compared to other guided media.

Unguided media (Wireless media)


A transmission media that does not require the use of cable for transmission of data is known as unguided
media.
1. Infrared Signals: In infrared transmission, signals are transmitted through the air but these signals
cannot penetrate the walls. Commonly Infrared signal are used in TV remotes, infrared wireless speakers,
etc., as a mode of transmission.

Advantage:

 It is secure medium of transmitting data.


 It is a cheap mode of transmission.

Disadvantage:

 It can work only for short distances.


 It cannot penetrate walls and is affected by distance, noise and heat.
Radio waves: It uses radio frequencies which are allocated to
private businesses for direct voice communication. A radio set up
uses transmitter and receiver, and both use antennas to radiate and
fetch radio signals.

Advantage:

 They can be used indoors or outdoors.


 Radio wave are Omni-directional and can travel in any direction.
 Radio wave transmission offers mobility.
 It is cheap then laying cables and fibres
 It offer ease of communication over difficult terrain.

Disadvantage:

 Radio wave communication is an insecure mode of communication.


 Radio wave propagation is susceptible to weather effects like rain, thunderstorm. etc.

Microwave: In this type of transmission, signals


are transmitted in the same way as the
radio waves. It is a line-of-sight transmission as
signal travels in straight line.
Under this mode of transmission parabolic
antennas are mounted on the towers. These
antennas send the signals in the atmospheric air.

Advantage:

 Using microwave, signals can be transmitted in


the air without using cables.
 Using microwave, communication is possible
even in difficult terrain or over oceans.

Disadvantages of Microwave

 It is not a secured mode of communication.


 Microwave communication is affected by weather conditions such as rain, thunderstorms, etc.

Satellite link: It is also a line-of-sight transmission, as signal


travels in straight line, that is used to transmit signal
throughout the world.
Advantage:

 The area covered is quite large.


 No line of sight restrictions such as mountains, tall buildings, towers, etc.
 Earth station which receives the signals can be at a fixed position or can be relatively mobile.
 This mode of transmission is very useful in multimedia transmission.

Disadvantage:

 Satellite communication is very costly. So, it is not suitable for personal or low budget communication.
 There is atmospheric loss of transmitted signals.

Bluetooth: is a wireless technology, which is used for exchanging data over short distances from fixed and
mobile devices. Such types of networks are categorized under personal area network.
Wifi: (wireless fidelity)Wi-Fi is a wireless networking technology that allows devices such as computers
(laptops and desktops), mobile devices and other equipment (printers and video cameras) to interface
with the Internet.
Wimax: It is a wireless communication system that provides broadband internet accessibility up to 30
miles. Such types of networks are categorized under MAN.

Chapter 7: Computer Networks (Part 3) For Video Lecture Click Here:

Network Devices:
Some Network devices are Modem, Ethernet card (NIC), RJ45, Repeater, Hub,
Switch, Router, Gateway, WIFI card, Bridge.
Modem:

 Modem is short form of Modulator Demodulator.


 It is a device which convert digital signal to analog signal and vice versa.
Types of Modem:

 Internal Modem: The modems that are fixed within the computer.
 External Modem: The external modems that are connected externally to a
computer as other peripherals are connected.

RJ-45: (Registered Jack – 45) It is an eight wired connector that is used to connect
computers on a local area network (LAN), especially Ethernet cable.

NIC

 NIC stands for Network Interface Card. It is also known as Ethernet Card.
 This device helps the computer to connect to a network and
communicate.
 It contain RJ-45 slot to connect Ethernet cable with RJ-45 connector.
HUB:

 HUB is used to connect multiple computers in a single LAN network of


one workgroup.
 Generally HUBs are available with 4,8,12,24,48 ports.
 It is simply copies the data to all of the nodes connected to the hub.
That’s why it is known as unintelligent network device.
 Because of copies data to all node it generates unnecessary traffic.
Types of HUB:
1) Passive Hub: It only forwards the signal on all ports without amplifying the signal.
2) Active Hub: It forwards the signal with improvement in the quality of data signal by amplifying it. That why
such hubs need additional power supply.
Switch:

 Switch is also used to connect multiple computers together in a


LAN workgroup, just like hub.
 Switches are available with 4,8,12,24,48,64 ports.
 But, Switch makes their switching decisions means, it sends
signal only to one port or recipient only and that’s why
switches are called as intelligent hub.
 Because of sending data only to one node it not generating
unnecessary traffic

Bridge:

 A bridge is a device that links two network together.


 Bridges are smart enough to know which computer are on
which side of bridge, so they only allow those messages that
need to get to the other side to cross the bridge.
 Bridges can handle networks that follow same protocol.

Gateway:

 A gateway is a device that connects dissimilar protocols.


 It establishes an intelligent connection between a local area
networks with completely different structures.

Repeater: A repeater is a device that amplifies and restore signals for long distance transmission.
Router:

 A router connects a local area network to the internet.


 This device works like bridge but can handle different
protocols.
 The router is responsible for forwarding data from one
network to a different network.

Wi-Fi Card:

 This is a small and portable cards that allows your computer to connect to the
internet through a wireless network.
 Data transmission is through the radio waves, these signals are picked up by Wi-Fi
receivers such as computers and cell phones equipped with Wi-Fi cards.

Chapter 7: Computer Networks (Part 4) For Video Lecture Click Here:

Network Topology: The way or style of connecting several computer/devices in a network with each
other is called topology.

Bus Topology: In Bus topology several devices are


connected to a main long cable (Usually coaxial cable)
which acts as backbone.
Advantages:

 Bus network is easy to implement and can be extended


up to a certain limit.
 It work well for small network.

 If there is any problem in connection with any node,


other nodes in the network are not affected.
Disadvantages:

 If there is fault or break in the main cable, the entire network shuts down.
 Terminators are required at both ends of the backbone cable.
 Fault isolation is difficult to detect if the entire network shuts down.
 When the network is required in more the than one building, bus network cannot be used.
 The signal becomes weaker if number of nodes becomes large.
 Collision of data can take place because several nodes can transmit data to each other at one time.

Star Topology: In star topology, the server is directly connected with each and every node in the network
via a hub.
Advantages:

 Data transfer rate is fast as all the data packets or messages


are transferred through central hub.

 If there is any problem in connection with any node, other


nodes in the network are not affected.
 Removal or addition of any node in star topology can take
place easily without affecting the entire performance of the
network.
Disadvantage:

 Extra hardware required like HUB.


 Any problem in hub makes the entire network shutdown.
 Performance of all network is depend on hub. If server is slow, it will cause the entire network slow down.
 More cable is required as compare to bus topology.

Ring Topology: In ring topology every computer is connected to the


next computer in the ring and each transmit the signal ,what it
receives from the previous computer. The messages flow around
the ring in one direction.
Advantages:

 Short cable length is required as compare to star topology for


connecting the nodes together.
 Data transmission rate is high because data transmit only on one direction

Disadvantages:

 If there is a fault in a single node, it can cause the entire network to fail.
 If there is a fault or break in cable, the entire network shut down.
 For proper communication between each node, each computer must be turned on.
Tree Topology: The tree topology is an extension and
variation in bus topology. In this all or some of the devices
are connected to central hub, and some of the device are
connected to the secondary hub. In case of long distance
networking we use active hub, it contain repeaters that
makes weak signals stronger.

Advantage:

 Tree topology is used when a start or bus cannot be implemented individually.


 It is most suited networking style to connect multiple departments of organization.
 Network can be expanded by the addition of secondary active hub.

Disadvantage:

 Multiple segment are connected to a central HUB. Its failure affects the entire network.
 There is a requirement of long cable length.
 Maintenance is not easy and cost is very high.

Network Types: On the basis of coverage or geographical spread, a network can be divided into following
types:

Personal Area Network (PAN) : The network that is belongs to a


single person or user is known as PAN. PAN is a small network used
to establish communication between a computer and other
handheld devices in the proximity of up to 10 meters using wired or
wireless medium like Bluetooth, WIFI or USB cable.
Examples: Wi-Fi network between Laptop and Mobile, Or
Bluetooth network between mobile and audio players.

Local Area Network (LAN): LAN is used to connect small


geographical area, like a home, office, or building such as a
school. Range of LAN is few meter to few kilometers. The
connectivity is done by means of wires, Ethernet cables, fibre
optics or Wi-Fi.
Examples: A networked office building, school or home.

Metropolitan Area Network(MAN):– Spread within a city . Cover


an area of a few kilometers to a few hundred kilometers radius.
Set up using all types of all guided and unguided media. Owned
and operated by a government body or a large corporation.
Example: Cable television networks available in the whole city or
interconnected offices in same city but in different areas.
Wide Area Network (WAN): A WAN interconnects all the
computer across the world. Internet is the largest WAN that
connects billions of computers, Smartphone and millions of LANs
of different continents. All guided or Unguided medium are used
to setup a WAN.
Example: Networks of ATMs, Banks, government offices, railway
reservation, etc.

Chapter 7: Computer Networks (Part 5) For Video Lecture Click Here:

Network Protocol: A network protocol is an established set of rules that determine how data is
transmitted between different devices in the same network.

Types of Network Protocol:

a) TCP/IP (Transmission Control Protocol) f) POP3 (Post office protocol)


b) HTTP g) VoIP (Voice over Internet Protocol )
c) HTTPS h) PPP (Point to point Protocol)
d) Telnet i) SMTP ( Simple Mail Transfer Protocol )
e) FTP (File Transfer Protocol)

Types of Wireless / Mobile Communication Protocol:

a) GSM (Global system for Mobile b) GPRS (General Packet Radio c) WLL (Wireless in Local Loop)
Communication) Services)

Types of Network Protocol:

TCP/IP(Transmission Control Protocol / Internet Protocol) :


TCP/IP is a set of two protocols. The TCP is responsible for breaking data into small packets to be
transmitted over the network. It is also responsible for reassembling the packets at the destination
computer.

IP: The IP part handles the address of the destination computer so that the data is send to a correct
address.

HTTP (Hypertext Transfer Protocol): HTTP is the communication protocol for transferring of information
on the internet and the world wide web. When we access any website on internet HTTP protocol is
working in background. (http://www.google.com)

HTTPS (Hyper Text Transfer Protocol Secure): It is a standard protocol to secure the communication
between the browser and the web server. In HTTPS transferring of data is done in an encrypted format to
get protect data from hackers. (https://www.google.com)

Telnet: It is also known as Remote login. This protocol allows you to access a remote computer connected
on the network. Example: teamviewer, anydesk

FTP (File Transfer Protocol): FTP allows users to transfer files from one machine to another, like Uploading
and Downloading. Types of files may include program files, multimedia files, text files, and documents, etc.
POP3 (Post office protocol): POP3 is designed for receiving incoming E-mails.

SMTP ( Simple Mail Transfer Protocol ): It is used to for sending email messages to other computer. It
handle only out going messages and not incoming messages.

VoIP (Voice over Internet Protocol ) : This Protocol that allows you to make voice calls using a broadband
Internet connection instead of a regular (or analog) phone line.

PPP (Point to point Protocol): It is most commonly used data link protocol. It is a protocol used to
establish a direct connection between two nodes. It is used to connect the Home PC to the server of ISP by
telephone line. This communication takes place through high speed modem.

Types of Wireless / Mobile Communication Protocol:

GSM (Global System for mobile Communication): GSM is a wireless communication medium that
provides the user with roaming facility, good voice quality, SMS, etc, through digital signals. It is also
known as 2G mobile technology.

GPRS (General Packet Radio Services): GPRS provides high speed data transfer. A user is allowed to
download video streaming, audio files, email messages, etc. It is also known as 2.5G Mobile technology.

WLL : WLL stands for Wireless in Local Loop. It provides user wireless phone facility to communicate with
each other.

Chapter 7: Computer Networks (Part 6) For Video Lecture Click Here:

Introduction to Web Services:

WWW (World Wide Web):

 The term www invented by Tim Burners Lee.


 It is a collection of linked HTML document or web pages, stored on millions of
computer and distributed across the internet.
 We can access graphics, audio and video file easily.

HTML (Hyper Text Markup Language):

 HTML is a language that enables users to create WebPages and format them using
predefined tags. Tags are called coded elements.
 HTML document can be written using text editor such as NOTEPAD and save in
.HTM or .HTML.
 Some HTML tags are: <HTML>, <HEAD>, <BOBY>
XML (Extensible Markup Language):

 XML is a text based markup language that allows the user to create their own tags to store data in a
structured format.
 XML is designed to carry data and not to display data.

Domain Name:

Domain name is the address of your website that people type in the browser’s URL bar to visit your
website.

Domain Name System (DNS) is the system for mapping


website names to numeric Internet Protocol (IP)
addresses like a book index maps a topic name/chapter
name to a specific page number.
Example :
Domain name: Google.com
IP address : 192.168.0.1

URL:

URL stands for Uniform Resource Locator which is a unique address of a webpage.

Website:

A website is a collection of web pages and related content that is


identified by a common domain name and published on at least
one web server. Notable examples are wikipedia.org,
google.com, and amazon.com.

Web page - A html document which can be displayed in a web


browser

Web Browser:

A web browser is application software for accessing the World Wide Web. When a user requests a web
page from a particular website, the web browser retrieves the necessary content from a web server and
then displays the page on the user's device.

Web Server:

A software which host website and return web pages to


web client(web browser) on request. E.g. Apache
Tomcat, Microsoft’s Internet Information Services (IIS)
Windows Server, Jigsaw , Zeus web server

Web Hosting:

Web hosting is the place where all the files of your website live. It is like the home of our website where it
actually lives.
Mobile Telecommunication Technologies:

1G Technology: 1G technology was used in the first mobile phones. 1G was


introduced in the 1980’s. Transmission of voice data took place through analog
radio signals. 1G network was used for voice calls and not for transmitting text
messages. Example: NMT, C-nets, AMPS, TACS

Features of 1G technology:

 It provides data rate up to 2.4 kbps.


 It uses analog signals.
 Voice quality is not very good.
 It does not support transmission of text messages.
 It does not provide security.

2G Technology: 2G Technology is the first digital cellular system that was launched
in the early 1990’s that provides high data transmission rate in digital format. 2G
also introduced data services for mobiles, starting with SMS. For example, D-
AMPS, GSM/GPRS, CDMA one.

Features of 2G technology:

 Good quality of sound.


 Higher data rates up to 64 kbps.
 Improved security mechanism
 Transmission of data such as text messages in digital format.
 Support transfer of picture message and MMS
 It does not support transfer of complex data such as videos.

3G Technology: 3G Technology was introduced in year 2000 and provides


much higher data rates with speed from 144kbps to 2mbps.

Features of 3G technology:

 It is used for faster web services


 Live chat, fast downloading, video conferencing is possible over mobile
phone.
 It allows to the user to play 3D games.
 A user can see live streaming on smart phones.
 High quality voice transmission.
4G Technology: 4G Technology gives ultra high broadband
internet services with faster data speed, typically between 100
Mbps - 1Gbps. 4G is also referred to as ‘MAGIC’ (Mobile
multimedia; Anytime/Anywhere; Global mobility support;
Integrated wireless solution; Customized personal services).

Features of 4G technology:

 It is used for internet access on computer also and is totally


wireless.
 It provide ‘anytime, anywhere’ voice and data transmission at a
much faster speed than 3G.
 Its provide high quality live streaming.

5G Technology: 5G is currently under development technology. 5G is


expected to allow data transfer in gbps, which is much faster than
4G. It is expected to be able to support all the devices of the future
such as connected vehicles and IOT ( Internet of things)
Chapter 8: Database Management For Video Lecture Click Here:

What is Database:

 A Database is a collection of data or


information, that is organized so that it
can be easily accessed, managed and
updated.

 In Database, Data is organized into rows,


columns and tables, and it is indexed to
make it easier to find relevant
information.

Use of database in Real life Applications:

Application Database to maintain data about


Banking Customer information, Account details, Loan details, Transaction details,
etc.
Inventory management Product details, customer information, Order details, Delivery data, etc.
Organization Resource Employee records, Salary details, Department information, Branch location.
management
Online Shopping Item description, User login details, User order details, etc.

Need of database or Database importance or Advantages of database:

 Elimination of data redundancy: It removes duplication of data because data are kept at one place
and all the application refers to the centrally maintained database.
 Sharing of data: Same database can be used by various platforms.
 Manages large amounts of data: A database stores and manages a large amount of data on a daily
basis. This would not be possible using any other tool such as a spreadsheet.
 Data is logically accurate: Through validation rule in database ,data accuracy can be maintained.
 Easy to update data: In a database, it is easy to update data using various Data Manipulation
languages (DML) available. One of these languages is SQL.
 Security of data: There are user logins required before accessing a database. It allows only
authorized users to access the database.

What is DBMS:

 A DBMS refers to a software that is responsible for storing, maintaining and utilizing database in an
efficient way.
 A Database along with DBMS software is called Database System.
 Example of DBMS software are Oracle, MS SQL Server, MS Access, Paradox, DB2 and MySQL etc.
Advantages of DBMS or Need of DBMS or Importance of DBMS:

 Database Maintenance: It helps in maintenance of data and database by addition, deletion,


modification, and regular updating of the tables and its records.
 Easy Retrieval: With the help of DBMS user can retrieves any particular information with the help
of different queries offers by DBMS software.
 Security of data: There are user logins required before accessing a database. It allows only
authorized users to access the database.

DBMS Model: Data model is a model or presentation which shows How data is organized ? or stored in the
database. Data models are categorized into four categories:

Relational Data Model:


In this model data is organized into Relations or Tables
(i.e. Rows and Columns). A Row is also called a Tuple
or Record. A Column is also called Attribute or Field.

Basic Terminologies related to Relational Database:


Relation: The table is also called relation. It is arranged
in Rows and Columns.

Attribute/Field: Column of a table is called Attribute


or Field. Example Sid, Sname, Sage, Sclass,
Ssection.
Tuple / Entity / Record - Rows of a table is
called Tuple or Record.

Domain : It is collection of values from which


the value is derived for a column.

Degree - Number of columns (attributes) in a


table.

Cardinality - Number of rows (Records) in a


table.

Keys in a Database:
Key plays an important role in relational database; it is used for identifying unique rows from table &
establishes relationship among tables on need.
Types of keys in DBMS:
Primary Key: A primary is a column or set of columns in a table that uniquely identifies tuples (rows) in
that table.
Candidate Key: A candidate key is one that is capable of becoming the primary key.
Alternate Key: Out of all candidate keys, only one gets selected as primary key, remaining keys are known
as alternate or secondary keys.
Foreign Key: Foreign keys are the columns of a table that points to the primary key of another table. They
act as a cross-reference between tables .
Chapter 9: SQL (Structured Query Language) For Video Lecture Click Here:

What is SQL:
SQL is a language that is used to create, modify and access a database. SQL is being used by many
database management systems. The SQL language was originally developed at the IBM research laboratory
in 1970. Some of them are: MySQL, PostgreSQL, Oracle, SQLite, Microsoft SQL Server.

MySQL: MySQL is an open-source and freely available Relational Database Management System (RDBMS)
that uses Structured Query Language (SQL). It provides excellent features for creating, storing, maintaining
and accessing data, from database.

Advantages / Features of SQL / MySQL:

 Interactive Language : This language can be used for communicating with the databases and used
to manage database.
 Portability : SQL is compatible with other database programs like Dbase IV, FoxPro, MS Access,
DB2, MS SQL Server, Oracle, Sybase, MySQL.
 No coding needed : It is very easy to manage the database systems without any need to write the
substantial amount of code by using the standard SQL.
 Not case-sensitive language : SQL is not a case-sensitive language, both capital and small letters
are recognized.

Types of SQL:

Data Definition Languages Data Manipulation Languages


All the commands used to create, modify or delete All the commands used to create, modify contents
physical structure of an object like table of a table
Example of Command: create, alter, drop. Example of Command: Insert, Delete, Update.

Data Types in MySQL:


Numeric Data type:

 INTEGER – It stores up to 11 digit number without decimal.


 SMALLINT - It stores up to 5 digit number without decimal.
 FLOAT(x,y) - It stores number in decimal format, where x is the size of total number of digits and y
is numbers of decimals. Example of float(4,2): 95.50
Date & Time Data types:

 DATE – It stores date in YYYY-MM-DD format..


 TIME - It stores time in HH:MM:SS format.

String or Text Data types:

 CHAR(size) – It stores a fixed length string from 0 to 255 characters. (default is 1)


 VARCHAR(size) - It stores a variable length string from 0 to 65535 characters.

Chapter 9: SQL (Structured Query Language) Part 2 For Video Lecture Click Here:

Database Commands in MySql:


1. SHOW DATABASES: Getting listings of available databases
Mysql> show databases;

2. CREATE DATABASE: This command is used to create a database in RDBMS.


Mysql> create database school;

3. Use: After database creation we can open the database using USE command.
Mysql> Use school;

4. Drop database: To physically remove or delete a database along with all its table, DROP command is
used.
Mysql> Drop database school;

5. CREATE TABLE: CREATE TABLE command is used to create a table in a database.


mysql> create table student2
-> (rno int,
-> name varchar(20),
-> gender char(1),
-> marks int,
-> dob date)
6. SHOW TABLES: To verify that the table has been created in the database, SHOW TABLES command in
used.
mysql> show tables;

7. DESCRIBE: To view a table structure, DESCRIBE or DESC command is used.


mysql> describe student;

8. ALTER TABLE: To modify a table structure, ALTER TABLE command is used.


1. Add a column to an existing table:
alter table student add city varchar(20);

2. Adding a column with default value:


alter table student add city1 varchar(20) default 'delhi';
3. Modifying an existing column definition or data type:
alter table student modify name varchar(40);

4. Renaming existing column:


alter table student change city state varchar(40);

5. Removing or drop column:


mysql> alter table student drop state;

9. DROP TABLE Command: To remove or delete any table permanently, DROP TABLE command is
used.
mysql> drop table student;

Chapter 9: SQL (Structured Query Language) Part 3 For Video Lecture Click Here:

Database Commands in MySql:


10. INSERT INTO: The INSERT INTO command is used to insert a new record/row/tuple in a table.
1. Inserting data for all the columns into table:
mysql> insert into student values(1,'raj','m',93,'2000-11-17');

2. We can insert data by specifies both the column names and the values to be inserted:
mysql> insert into student (rollno, name, gender, marks,dob)
values(2,NULL,'m',93,'2000-11-17');

3. Inserting data into specific columns of table:


mysql> insert into student (rollno, name, gender,dob)
values(2,NULL,'m','2000-11-17');

4. Inserting NULL values into a table:


insert into student (rollno, name, gender, marks, dob)
values(2,'Ravi',NULL,93,'2000-11-17');

Note*- Null means unavailable or undefined value.


11. SQL SELECT Statement: The SELECT command in SQL is used to fetch/get data from one or more
database tables. It is used to select rows and columns from a database or relation.
1. To Fetch/Select full table data:
mysql> select * from students;

2. To Fetch/Select specific attributes from table:


mysql> select name, city from students;

3. To Fetch/Select specific row from table using WHERE Clause:


mysql> select * from students where rollno=3;

4. To re-ordering of column while displaying query result:


mysql> select name, rollno from students where rollno=3;
5. To eliminating duplicate/Redundant data using DISTINCT Clause:
mysql> select distinct city from students;

12. Modifying data in table: The UPDATE command in SQL is used to modify data in table using the
WHERE clause and the new data is written in place of old data using the SET keyword.
1. To Update single or multiple columns:
mysql> update students set city="Fatehpur" where rollno=1;

mysql> update students set name="janvi", gender='f' where


name='deep';

2. Updating to NULL values:


mysql> update students set dob=Null where city='delhi';

3. Updating using an expression or formula:


mysql> update students set percent= percent+5 where (rollno=2 or
rollno=4);

13. Removing data from a table: The DELETE command in SQL is used to delete rows from a table using
WHERE clause.
delete from students2 where rollno=3;

14. Removing all data from a table: The TRUNCATE command in SQL is used to delete all rows from a table
free the space containing table.
truncate table students2;

Chapter 9: SQL (Structured Query Language) Part 4 For Video Lecture Click Here:

Constraints in MySQL:

 The constraint in MySQL is used to specify the


rule that allows or restricts what values/data
will be stored in the table.
 They provide a suitable method to ensures
data accuracy inside the table.
 It also helps to limit the type of data that will
be inserted inside the table.

Creating Table with Constraints


The following constraints are commonly used in SQL:
1. Primary key Constraint:
 It is used to uniquely identify each record in a table.
 Primary Key values must not be NULL.
 There must be a single column only having Primary Key Constraint.
2. Unique Constraint:
 The purpose of a unique key is to ensure that the information in the column for each row must
be unique.
 Unique key Constraint can have NULL values.

3. Not Null Constraint:


 The column having NOT NULL constraint cannot contain NULL values, but it can be repeat.

4. Default Constraint:
 Default constraint is used to assign the default value to a column, when user does not provide
any value.
 However, if a user provide any value, then it will be overwrite.

5. Check Constraint:
 The CHECK constraint ensures that all the values in a column satisfies certain conditions.

Chapter 9: SQL (Structured Query Language) Part 5 For Video Lecture Click Here:

Operators in MySQL:
There are mainly three types of operators in MySQL.

Arithmetic Operators: Arithmetic operators used to perform simple arithmetic operations like addition (+),
Subtraction (-), multiplication (*), division(/), Modulus (%).

Example: mysql> select name, salary, salary+5000 from emp;

Relational Operators:

 A relational (comparison) operators is a Operators Description


mathematical symbol which is used to = Equal to
compare two values or expression. And > Greater than
give results in ‘true’ or ‘false’ < Less than
 It is used to compare two values of the >= Greater than or equal to
same or compatible data types. <= Less than or equal to
 They are used with WHERE clause. <>,!= Not equal to

Example: mysql> select * from emp where age>=22;

Logical Operators:
The SQL logical operators are the operators used to combine multiple conditions and filter data on the
basis of the condition specified in an SQL statement. Logical operators are also known as Boolean
operators.
There are three types of operators are:
AND operators: The AND operator displays a record and returns a true if all conditions (usually two
conditions) specified in the WHERE clause are true.
Example: mysql> select * from emp where salary > 20000 and age < 25;

OR operators: The OR operator displays a record and returns a true if either of the conditions (usually two
conditions) specified in the WHERE clause is true.

Example: mysql> select * from emp where salary > 20000 or age > 25;

NOT operators: NOT operators is also termed as a negation operator. This operator takes only one
condition and gives the reverse of it as the result.
Example: mysql> select * from emp where not age > 22;

Some Special Operators in MySQL:

Between
This operator defines the range of values that the column values must fall into make the condition True.
The range includes both the upper Values as well as Lower Values.
Example: select * from emp where salary between 15000 and 20000;

Not Between
The NOT BETWEEN operators works opposite to the BETWEEN operators. It retrieves the rows which do
not satisfy the BETWEEN condition.
The range not includes both the upper Values as well as Lower Values.
Example: select * from emp where salary not between 15000 and 20000;

IN
This operator selects values that match any values in the given list. The SQL IN condition is used to help
reduce the need for multiple OR conditions in a SELECT statement.
Example: select * from emp where salary in (15000,20000,25000);
NOT IN
The NOT IN operators works opposite to IN operator. It matches, finds and returns the rows that do not
match the list.
Example: select * from emp where salary not in (15000,20000);

IS NULL
THE IS NULL is used to search for null values in a column.
mysql> select * from emp where salary is null;
IS NOT NULL
THE IS NOT NULL is used to search for not null values in a column.

mysql> select * from emp where salary is not null;

Chapter 9: SQL (Structured Query Language) Part 6 For Video Lecture Click Here:

Like
The LIKE operators is used to search for a specified pattern in a column. This operator is used with the
columns of types CHAR and VARCHAR.
SQL provides two Wild Card Characters that are used while comparing the strings with LIKE operators:

 Percent(%) The % character matches any substring.


 Underscore(_) The _ character matches any one character.
To display those records where name is begins with character “D”.
mysql> select * from emp where name like "D%";
To display those records where name is ends with the letter “a”
mysql> select * from emp where name like "%a";
To display those records where name contains any character anywhere in it.

mysql> select * from emp where name like "%i%";


To display those records where name contains the letter ‘a’ at the second place.
mysql> select * from emp where name like "_a%";
To display those records where name contains the letter ‘a’ at the second last position.
mysql> select * from emp where name like '%a_';

To display those records where name contains only 5 characters.


mysql> select * from emp where name like '_ _ _ _ _';
Not Like
The NOT LIKE operator gives just opposite data of LIKE operators.

Chapter 9: SQL (Structured Query Language) Part 7 For Video Lecture Click Here:

Aggregate Functions in MySQL:


An aggregate function performs a calculation on multiple values and returns a single value. For example,
you can use the AVG() aggregate function that takes multiple numbers and returns the average value of
the numbers. Following is the list of aggregate functions supported by mysql.
SUM(): SUM() function is used to find the total value of any column or expression based on a column.
mysql> select sum(age) from emp;
MIN(): MIN() function is used to find the lowest value among the given set of values of any column or
expression based on the column.
mysql> select min(age) from emp;

MAX(): Max() function is used to find the highest value among the given set of values of any column or
expression based on the column.

mysql> select max(age) from emp;

AVG(): AVG() function is used to find the average value of any column or expression based on column.
mysql> select avg(age) from emp;

COUNT(): COUNT() function is used to count the number of values in a column. COUNT() returns the
number of non-null values in that column. If the argument is asterisk (*) then count() counts the number
of records/rows including Null values.
mysql> select count(age) from emp;
mysql> select count(*) salary from emp;
mysql> select count(distinct age) from emp;

Aggregate Functions & NULL values:


In case of NULL values none of the aggregate
functions takes NULL into consideration.
NULL values are simply ignored by all
aggregate functions.

Chapter 9: SQL (Structured Query Language) Part 8 For Video Lecture Click Here:

PUTTING TEXT IN THE QUERY


With this option, we can include some user-
defined columns at runtime. These columns
are displayed with a valid text, symbols and
comments in the output only. This makes the
query output more presentable by giving a
formatted output.
Example:
select rno , name , 'has scored' , marks from student;

ALIASES
SQL aliases are used to give an alternate name or temporary name, to a
column in a table. Name changes temporarily and does not changes the
actual name in the database. They are created to make column name
more readable.

For Column:
select name as "Employee name" from emp;

ORDER BY
The SQL ORDER BY clause is used to sort the data in ascending order or descending order based on one or
more columns. This clause sorts the records in the ascending order (ASC) by default. And in order to sort
the records in descending order, DESC keyword is to be used.
select * from emp order by age;
select * from emp order by age desc;

select * from student order by stream asc ,name desc ;

GROUP BY
The GROUP BY clause combines all those records that have identical values in a particular field.
Grouping can be done with aggregate functions, such as SUM, AVG, MAX, MIN, and COUNT.

mysql> select stream, count(*) from student group by stream;


mysql> select stream, count(*),sum(marks) from student group by stream;
mysql> select gender, count(*),sum(marks),max(marks) from student group by gender;

HAVING clause
The purpose of HAVING clause with GROUP BY is to aggregate functions to be used along with the
specified condition because the aggregate functions are not allowed to be used with WHERE clause.
mysql> select stream, count(*) from student group by stream having count(*)>3;
SQL Joins: For Video Lecture Click Here:
SQL JOIN clause is used to combine rows from two or more tables, based on a common field between
them.
The types of SQL joins are as follows:

1. Cartesian product (Cross Product)


2. Equi Join
3. Natural Join

Cartesian Product (Cross Product)


The Cartesian product is also termed as
cross product or cross-join. The Cartesian
product is a binary operation and is
denoted by X.

The number of tuples in the new


relation(table) is equal to the product of
the number of tuples of the two tables on
which Carterian product is performed.
For example:

mysql> select * from emp,dep;

Equi Join
An Equi join is a simple SQL join condition that uses the equal to sign(=) as a comparison operator for
defining a relationship between two tables on the basis of common filed, primary key and foreign key.
Here, column with the same name appears two times.
mysql> select * from emp,dep where emp.d_no=dep.d_no;
or
mysql> select * from emp join dep on emp.d_no=dep.d_no;

Natural Join
The SQL Natural Join is a type of Equi Join and is structured in such a way that columns with the same
name of associated tables will appear only once.
In NATURAL JOIN, the join condition is not required, it automatically joins based on the common column
value.

mysql> select * from emp natural join dep;


Chapter 10 : Interface of python with an SQL database (Part -1) For Video Lecture Click Here:

Connecting SQL with Python (Establishing Connection)


Import mysql.connector: This statement imports the Mysql Connector Python module in your program. In
case of connection fails, its show error.

mysql.connector. connect(): The connect() statement creates a connection to the Mysql server and return
a Mysql Connection object.

This function required four parameters: host, database, user and password.

mydb.is_connected(): This function is used to verify that our python application is connected to Mysql.
Here, mydb is Mysql Connection object.

Way to create Connection between SQL and Python is given Below:

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",password="123456")
print(mydb)

mydb.cursor():This function returns a cursor object. Using a cursor object, we can execute SQL queries.
Cursor object interact with the MySQL server using a Mysql Connection object.

execute():The execute() method accepts arguments of SQL statements in string format, enclosed in double
quotes(“ ”).

Creating database in Mysql through Python:

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",password="123456")
mycursor=mydb.cursor()
mycursor.execute("create database demo")

Show database in Mysql through Python:

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",password="123456")
mycursor=mydb.cursor()
mycursor.execute("Show databases")
for i in mycursor:
print(i)

Drop database in Mysql through Python:

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",password="123456")
mycursor=mydb.cursor()
mycursor.execute("drop database demo")
Creating table inside any database through Python:

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",password="123456",database="school")
mycursor=mydb.cursor()
mycursor.execute("create table std_details3(rno int primary key,name varchar(20), age int, city
varchar(20))")

Change in table structure inside any database through Python:

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",
password="123456",database="school")
mycursor=mydb.cursor()
mycursor.execute("alter table student add(city varchar(20))")

Chapter 10 : Interface of python with an SQL database (Part -2) For Video Lecture Click Here:

mycon.commit(): While working on insert, update and delete operation commit() is used to
show changes in table data.

Inserting Records into table


import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",
password="123456",database="school")
mycursor=mydb.cursor()
mycursor.execute("insert into student values(10,'Mukesh','M',89,'Arts','Kanpur')")
mydb.commit()

Updating Records into table


import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",
password="123456",database="school")
mycursor=mydb.cursor()
mycursor.execute("update student set city='Delhi' where rno=3")
mydb.commit()

Deleting Records into table

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",
password="123456",database="school")
mycursor=mydb.cursor()
mycursor.execute("delete from student where rno=2")
mydb.commit()

Chapter 10 : Interface of python with an SQL database (Part -3) For Video Lecture Click Here:

Display data by using fetchall(), fetchone(),fetchmany() and rowcount


What is the meaning of word fetch - The word fetch means to get or retrieve any particular data from the
database tables.
fetchall(): It fetch all the rows in a result set and returns a list of tuples. If some rows have already been
extracted from the result set, then it retrieves the remaining rows from the result set. If no more rows are
available, it return an empty list.

fetchone(): It fetch one record from the resultset as a tuple. First time, it will fetch the first record, next
time it will fetch the second record.

fetchmany(n): It fetches the specified number of rows from the result set. The defult size is 1.

rowcount: This is a read-only attribute and returns the number of rows that were affected by an execute()
method.

Display data by using fetchall()


import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",
password="123456",database="school")
mycursor=mydb.cursor()
mycursor.execute("select * from student")
myrecords=mycursor.fetchall()
for i in myrecords:
print(i)
print("Total number of rows retrieved",mycursor.rowcount)

Display data by using fetchone()


import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",\
password="123456",database="school")
mycursor=mydb.cursor()
mycursor.execute("select * from student")
myrecords=mycursor.fetchone()
print(myrecords)
print("Total number of rows retrieved",mycursor.rowcount)

Display data by using fetchmany()


import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",
password="123456",database="school")
mycursor=mydb.cursor()
mycursor.execute("select * from student")
myrecords=mycursor.fetchmany(5)
for i in myrecords:
print(i)
print("Total number of rows retrieved",mycursor.rowcount)

Chapter 10 : Interface of python with an SQL database (Part -4) For Video Lecture Click Here:

Parameterized Query for insert, update and delete operations


import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",password="123456",database="school")
mycursor=mydb.cursor()
y="y"
while y=="y":
r=int(input("Enter rollno:"))
n=input("Enter name:")
g=input("Enter gender:")
m=int(input("Enter Marks:"))
s=input("Enter Stream:")
c=input("Enter City:")
mycursor.execute("insert into student values({},'{}','{}',{},'{}','{}')".format(r,n,g,m,s,c))
mydb.commit()
print(mycursor.rowcount,"Record Inserted")
y=input("Do you want to insert more data:")

You might also like