SlideShare a Scribd company logo
1 of 32
www.sunilos.com
www.raystec.com
PDBC
www.SunilOS.com 2
SQL
It stands for Structured Query Language.
Standardized syntax for “querying” (accessing) a
relational database.
It is assumed that SQL is database independent but there
are important variations from Database to Database.
www.SunilOS.com 3
Sales System Tables
Order
id date part_id qty
1 2/12/2006 1 100
2 3/15/2006 2 200
3 3/15/2006 3 100
4 4/5/2006 2 300
5 4/15/2006 3 200
6 6/15/2006 1 400
7 8/1/2006 1 100
Part
id name color unit_id
1 Nut Grey 2
2 Bolt Grey 3
3 Screw Silver 2
Unit
id city Capacity
1 New York 1000
2 London 2000
3 Paris 3000
Primary Key
Foreign Key
Foreign Key
Primary
Key
www.SunilOS.com 4
SQL Statements
 DDL data definition language
o Statement for defining tables
 Create & Alter Tables
o Statement for deleting tables
 Drop table
 DML data manipulation language
o Statement for Queries
 SELECT * FROM part;
o Statement for Inserting and Updating data
 INSERT into part VALUES(4,'plat','Green',1);
 UPDATE part SET color = 'Green', unit_id = 1 where id=4;
o Statement for deleting rows
 DELETE FROM part WHERE id=4;
 DCL – Data Control Language
o Commit : Saves data changes
o Rollback : Reverts data changes
o Savepoint : transaction demarcation.
www.SunilOS.com 5
DDL Statements
CREATE TABLE `part` (
`id` int(11) NOT NULL,
`name` text,
`color` text,
`unit_id` int(11) default NULL,
PRIMARY KEY (`id`)
)
ALTER TABLE `part`
ADD `color` text/
www.SunilOS.com 6
DML Statements
 Statement to insert all columns into part table.
INSERT INTO part VALUES (4,'plat','Green',1);
 Statement to insert id and name columns into part table.
INSERT INTO part (id,name) VALUES (4,'plat');
 Statement to update color and unit_id into part table.
UPDATE part SET color = 'Green', unit_id = 1 WHERE id=4;
 Statement to delete record from part table.
DELETE FROM part WHERE id=4;
www.SunilOS.com 7
DML - Select
Get all parts
o SELECT * FROM part;
Get all parts’ ids, names and colors
o SELECT id, name, color FROM part;
Get all grey color parts
o SELECT * FROM part WHERE color = ‘Grey’
Get all parts sorted by name
o SELECT * FROM part ORDER BY name
www.SunilOS.com 8
DML – Aggregate Functions
How many parts are there?
o SELECT count(*) from part;
o SELECT count(id) from part;
How many parts have been sold?
o SELECT sum(qty) from order
Which is the biggest deal so far?
o SELECT max(qty) from order;
Which is the minimum deal so far?
o SELECT min(qty) from order;
www.SunilOS.com 9
Joins
 Get parts with their cities of units.
o Columns :part.id, name, color, unit.city
o Tables :part & unit
o Condition :part.unit_id = unit.id;
 SELECT part.id, name, color, unit.city FROM part, unit
WHERE part.unit_id = unit.id;
www.SunilOS.com 10
Aliases
 SELECT p.id PartID, name, color, u.city FROM part p,
unit u WHERE p.unit_id = u.id
 Or
 SELECT p.id as PartID, name, color, u.city FROM part as
p, unit as u WHERE p.unit_id = u.id
SQL IN/BETWEEN
 Get the list of all Silver and Grey parts.
o SELECT * FROM part WHERE color IN ('Grey','Silver')
 Get orders those ordered quantities are between 100 to 200.
o SELECT * from orders WHERE qty BETWEEN 100 AND 200
 Get part counts for each color.
o SELECT color, count (*) part FROM part GROUP BY color
www.SunilOS.com 11
www.SunilOS.com 12
Nested Query
A Query can be nested in another query.
Get part ids those are ordered more than 100.
o SELECT part_id FROM orders WHERE qty > 100
Get part names those are ordered more than 100.
o SELECT name FROM part
o WHERE id IN
o ( SELECT part_id FROM orders WHERE qty > 100)
www.SunilOS.com 13
Joins
Outer Join
Inner Join
Left Join
Right Join
Joins
www.SunilOS.com 14
SELECT * from TableAA
LEFT JOIN TableB B
ON A.Key = B.Key
SELECT * from TableAA
RIGHT JOIN TableB B
ON A.Key = B.Key
SELECT * from TableAA
OUTER JOIN TableB B
ON A.Key = B.Key
SELECT * from TableAA
INNER JOIN TableB B
ON A.Key = B.Key
www.SunilOS.com 15
PDBC Overview
Python Database Connectivity.
Python supports various databases like MySQL, Oracle,
Sybase etc.
We can use Python DB-API for database connectivity.
DB-API:-
o pymysql for mysql database.
o cx_Oracle for oracle database.
o pymssql for msSQL database.
www.SunilOS.com 16
MYSQL – Get Data
 import pymysql
 result=""
 connection = pymysql.connect(host='localhost',user='root',password='root',db='test')
 with connection.cursor() as cursor:
 sql = "select * from part"
 cursor.execute(sql)
 result= cursor.fetchall()
 connection.close()
 for d in result:
 print(d[0]," ",d[1],"t", d[2])

Column value by index
SQL Query
DB URL Login ID PWD
www.SunilOS.com 17
Connect with Database
Here are the steps to be followed to make a database
call:
1. Import that database specific module.
2. Make connection to the Database
3. Create Cursor object
4. Execute cursor.fetchall and get Result or execute
insert/update/delete query and get number of records affected
Note:First Install pymysql by command
o pip install pymysql
www.SunilOS.com 18
MYSQL – Insert/Update Data
 import pymysql
 import traceback
 try:
 connection = pymysql.connect(host='localhost',user='root',password='root',db='test')
 with connection.cursor() as cursor:
 sql = "INSERT INTO part (`ID`,`NAME`,`COLOR`)VALUES (%s,%s,%s)"
 try:
 cursor.execute(sql, (5, 'screw', 'silver'))
 connection.commit()
 print("Data add successfully")
 except Exception:
 connection.rollback()
 traceback.print_exc()
 print("Oops! Something wrong")
 finally:
 connection.close()

www.SunilOS.com 19
Cursor Methods
 cursor.fetchall()
o Executes an SQL statement and returns a Result.
 cursor.execute(String)
o Executes an SQL INSERT, UPDATE or DELETE statement and returns
the number of rows changed.
www.SunilOS.com 20
PDBC URLs
 ORACLE
Import cx_Oracle
Connection = cx_Oracle.connect(‘scott/tiger@localhost’)
 MSSQL
Import cx_Oracle
Connection = cx_Oracle.connect(‘scott/tiger@localhost’)
www.SunilOS.com 21
Stored Procedures
It is written in database specific language.
It is stored in database.
It is accessed by callproc.
o cursor.callproc(‘StoredProcedureName’)
www.SunilOS.com 22
Call to a Stored Procedure
 import pymysql
 import traceback
 connection = pymysql.connect(host='localhost',user='root',password='root',db='abc')
 with connection.cursor() as cursor:
 cursor.callproc(“userCount")
 for result in cursor.fetchall():
 print(result)
 connection.close()

www.SunilOS.com 23
MYSQL – User Count
DELIMITER $$
DROP PROCEDURE IF EXISTS `userCount`$$
CREATE PROCEDURE test.`userCount`()
BEGIN
SELECT COUNT(*) FROM users ;
END$$
DELIMITER ;
www.SunilOS.com 24
Transaction Handling
 A transaction is a set of data changes made by multiple SQL
statements. Entire changes of this set will be either committed
(saved) or rolled back (reverted) together.
 By default each statement is committed irrespective of others
failures.
 Transaction begins by:
o conn.autocommit = false;
o Default value of auto commit is true.
 Transaction ends by calling:
o connection.commit()
o conncetion.rollback();
www.SunilOS.com 25
Transaction Handling : Commit
import pymysql
Sql = "INSERT INTO company(`ID`,`NAME`,`ADDRESS`)VALUES (%s,%s,%s)"
connection = pymysql.connect(host='localhost',user='root',password='root',db='abc')
connection.autocommit = False
with connection.cursor() as cursor:
cursor.execute(sql, (109,‘NCS',‘Indore'))
cursor.execute(sql1, (109,‘Rays',‘Indore'))
connection.commit()
www.SunilOS.com 26
Mapping Python Types to SQL Types
SQL type Python Type
CHAR, VARCHAR, LONGVARCHAR String
NUMERIC, DECIMAL float
BIT bool
TINYINT int
SMALLINT int
INTEGER int
BIGINT int
REAL float
FLOAT, DOUBLE float
BINARY, VARBINARY, LONGVARBINARY byte.String
DATE datetime.date
TIME datetime.time
TIMESTAMP datetime.datetime
Date + Time
(Nano sec)
www.SunilOS.com 27
Database Time
python defines datetime module to handle date and time:
 datetime.date
o year, month, day
 datetime.time
o hours, minutes, seconds, microseconds
 datetime.datetime
o year, month, day, hours, minutes, seconds, microseconds
o By default Timestamp should be used
www.SunilOS.com 28
Metadata – Data about Data
 import pymysql
 connection = pymysql.connect(host='localhost',user='root',password='root',db='abc')
 with connection.cursor() as cursor:
 cursor.execute("select * from company ")
 cursor.fetchall()
 meta=cursor.description
 for data in meta:
 print("t",data[0],end="")
 connection.close()

www.SunilOS.com 29
Python Bean
Marksheet
-rollNo : String
-name : String
-chemistry : int
-physics : int
-maths:int
+setters
+getters
www.SunilOS.com 30
DAO
MarksheetDAO
+ add (Marksheet)
+ update (Marksheet)
+ delete (rollNo) : Marksheet
+ get (rollNo) : Marksheet
+getMeritList(): ArrayList
+search(Marksheet)
TestMarksheetDAO
+ testAdd ()
+ testUpdate ()
+ testDelete ()
+ testGet ()
+testGetMeritList()
+testSearch()
Disclaimer
This is an educational presentation to enhance the skill
of computer science students.
This presentation is available for free to computer
science students.
Some internet images from different URLs are used in
this presentation to simplify technical examples and
correlate examples with the real world.
We are grateful to owners of these URLs and pictures.
www.SunilOS.com 31
Thank You!
www.SunilOS.com 32
www.SunilOS.com

More Related Content

What's hot

Collections Framework
Collections FrameworkCollections Framework
Collections FrameworkSunil OS
 
Java 8 - CJ
Java 8 - CJJava 8 - CJ
Java 8 - CJSunil OS
 
Java Basics V3
Java Basics V3Java Basics V3
Java Basics V3Sunil OS
 
Collection v3
Collection v3Collection v3
Collection v3Sunil OS
 
Threads V4
Threads  V4Threads  V4
Threads V4Sunil OS
 
Exception Handling
Exception HandlingException Handling
Exception HandlingSunil OS
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and OperatorsSunil OS
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/ServletSunil OS
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4Sunil OS
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and ConcurrencySunil OS
 
Java Basics
Java BasicsJava Basics
Java BasicsSunil OS
 
Resource Bundle
Resource BundleResource Bundle
Resource BundleSunil OS
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for BeginnersJason Davies
 

What's hot (20)

Collections Framework
Collections FrameworkCollections Framework
Collections Framework
 
Java 8 - CJ
Java 8 - CJJava 8 - CJ
Java 8 - CJ
 
OOP V3.1
OOP V3.1OOP V3.1
OOP V3.1
 
Java Basics V3
Java Basics V3Java Basics V3
Java Basics V3
 
C++
C++C++
C++
 
Collection v3
Collection v3Collection v3
Collection v3
 
Threads V4
Threads  V4Threads  V4
Threads V4
 
JDBC
JDBCJDBC
JDBC
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and Operators
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
C Basics
C BasicsC Basics
C Basics
 
Log4 J
Log4 JLog4 J
Log4 J
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Resource Bundle
Resource BundleResource Bundle
Resource Bundle
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for Beginners
 

Similar to SQL and Database Fundamentals

Database Management System Review
Database Management System ReviewDatabase Management System Review
Database Management System ReviewKaya Ota
 
6_SQL.pdf
6_SQL.pdf6_SQL.pdf
6_SQL.pdfLPhct2
 
CS 542 Database Index Structures
CS 542 Database Index StructuresCS 542 Database Index Structures
CS 542 Database Index StructuresJ Singh
 
So I already have most of the code and now I have to1. create an .pdf
So I already have most of the code and now I have to1. create an .pdfSo I already have most of the code and now I have to1. create an .pdf
So I already have most of the code and now I have to1. create an .pdfarjuncollection
 
All Things Open 2016 -- Database Programming for Newbies
All Things Open 2016 -- Database Programming for NewbiesAll Things Open 2016 -- Database Programming for Newbies
All Things Open 2016 -- Database Programming for NewbiesDave Stokes
 
Polyglot ClickHouse -- ClickHouse SF Meetup Sept 10
Polyglot ClickHouse -- ClickHouse SF Meetup Sept 10Polyglot ClickHouse -- ClickHouse SF Meetup Sept 10
Polyglot ClickHouse -- ClickHouse SF Meetup Sept 10Altinity Ltd
 
Cobrix – a COBOL Data Source for Spark
Cobrix – a COBOL Data Source for SparkCobrix – a COBOL Data Source for Spark
Cobrix – a COBOL Data Source for SparkDataWorks Summit
 
SQL Server 2008 Portfolio
SQL Server 2008 PortfolioSQL Server 2008 Portfolio
SQL Server 2008 Portfoliolilredlokita
 
IBM Informix dynamic server 11 10 Cheetah Sql Features
IBM Informix dynamic server 11 10 Cheetah Sql FeaturesIBM Informix dynamic server 11 10 Cheetah Sql Features
IBM Informix dynamic server 11 10 Cheetah Sql FeaturesKeshav Murthy
 
DN 2017 | Reducing pain in data engineering | Martin Loetzsch | Project A
DN 2017 | Reducing pain in data engineering | Martin Loetzsch | Project ADN 2017 | Reducing pain in data engineering | Martin Loetzsch | Project A
DN 2017 | Reducing pain in data engineering | Martin Loetzsch | Project ADataconomy Media
 
Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateKiev ALT.NET
 
New Features of SQL Server 2016
New Features of SQL Server 2016New Features of SQL Server 2016
New Features of SQL Server 2016Mir Mahmood
 
Sql 99 and_some_techniques
Sql 99 and_some_techniquesSql 99 and_some_techniques
Sql 99 and_some_techniquesAlexey Kiselyov
 
Sql basics
Sql basicsSql basics
Sql basicsKumar
 

Similar to SQL and Database Fundamentals (20)

SQL Core Concept
SQL Core ConceptSQL Core Concept
SQL Core Concept
 
PostThis
PostThisPostThis
PostThis
 
Chapter 4 Structured Query Language
Chapter 4 Structured Query LanguageChapter 4 Structured Query Language
Chapter 4 Structured Query Language
 
Database Management System Review
Database Management System ReviewDatabase Management System Review
Database Management System Review
 
6_SQL.pdf
6_SQL.pdf6_SQL.pdf
6_SQL.pdf
 
CS 542 Database Index Structures
CS 542 Database Index StructuresCS 542 Database Index Structures
CS 542 Database Index Structures
 
So I already have most of the code and now I have to1. create an .pdf
So I already have most of the code and now I have to1. create an .pdfSo I already have most of the code and now I have to1. create an .pdf
So I already have most of the code and now I have to1. create an .pdf
 
All Things Open 2016 -- Database Programming for Newbies
All Things Open 2016 -- Database Programming for NewbiesAll Things Open 2016 -- Database Programming for Newbies
All Things Open 2016 -- Database Programming for Newbies
 
Polyglot ClickHouse -- ClickHouse SF Meetup Sept 10
Polyglot ClickHouse -- ClickHouse SF Meetup Sept 10Polyglot ClickHouse -- ClickHouse SF Meetup Sept 10
Polyglot ClickHouse -- ClickHouse SF Meetup Sept 10
 
C++ practical
C++ practicalC++ practical
C++ practical
 
Cobrix – a COBOL Data Source for Spark
Cobrix – a COBOL Data Source for SparkCobrix – a COBOL Data Source for Spark
Cobrix – a COBOL Data Source for Spark
 
Rdbms day3
Rdbms day3Rdbms day3
Rdbms day3
 
Sql commands
Sql commandsSql commands
Sql commands
 
SQL Server 2008 Portfolio
SQL Server 2008 PortfolioSQL Server 2008 Portfolio
SQL Server 2008 Portfolio
 
IBM Informix dynamic server 11 10 Cheetah Sql Features
IBM Informix dynamic server 11 10 Cheetah Sql FeaturesIBM Informix dynamic server 11 10 Cheetah Sql Features
IBM Informix dynamic server 11 10 Cheetah Sql Features
 
DN 2017 | Reducing pain in data engineering | Martin Loetzsch | Project A
DN 2017 | Reducing pain in data engineering | Martin Loetzsch | Project ADN 2017 | Reducing pain in data engineering | Martin Loetzsch | Project A
DN 2017 | Reducing pain in data engineering | Martin Loetzsch | Project A
 
Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicate
 
New Features of SQL Server 2016
New Features of SQL Server 2016New Features of SQL Server 2016
New Features of SQL Server 2016
 
Sql 99 and_some_techniques
Sql 99 and_some_techniquesSql 99 and_some_techniques
Sql 99 and_some_techniques
 
Sql basics
Sql basicsSql basics
Sql basics
 

More from Sunil OS

Threads v3
Threads v3Threads v3
Threads v3Sunil OS
 
Exception Handling v3
Exception Handling v3Exception Handling v3
Exception Handling v3Sunil OS
 
Python Pandas
Python PandasPython Pandas
Python PandasSunil OS
 
Angular 8
Angular 8 Angular 8
Angular 8 Sunil OS
 
C# Variables and Operators
C# Variables and OperatorsC# Variables and Operators
C# Variables and OperatorsSunil OS
 
Rays Technologies
Rays TechnologiesRays Technologies
Rays TechnologiesSunil OS
 
Java Swing JFC
Java Swing JFCJava Swing JFC
Java Swing JFCSunil OS
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File HandlingSunil OS
 

More from Sunil OS (11)

OOP v3
OOP v3OOP v3
OOP v3
 
Threads v3
Threads v3Threads v3
Threads v3
 
Exception Handling v3
Exception Handling v3Exception Handling v3
Exception Handling v3
 
Python Pandas
Python PandasPython Pandas
Python Pandas
 
Angular 8
Angular 8 Angular 8
Angular 8
 
C# Variables and Operators
C# Variables and OperatorsC# Variables and Operators
C# Variables and Operators
 
C# Basics
C# BasicsC# Basics
C# Basics
 
Rays Technologies
Rays TechnologiesRays Technologies
Rays Technologies
 
C++ oop
C++ oopC++ oop
C++ oop
 
Java Swing JFC
Java Swing JFCJava Swing JFC
Java Swing JFC
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 

Recently uploaded

Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQuiz Club NITW
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptxDhatriParmar
 
Shark introduction Morphology and its behaviour characteristics
Shark introduction Morphology and its behaviour characteristicsShark introduction Morphology and its behaviour characteristics
Shark introduction Morphology and its behaviour characteristicsArubSultan
 
How to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineHow to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineCeline George
 
Objectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxObjectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxMadhavi Dharankar
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDhatriParmar
 
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFEPART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFEMISSRITIMABIOLOGYEXP
 
DiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdfDiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdfChristalin Nelson
 
4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptxmary850239
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxSayali Powar
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdfMr Bounab Samir
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...Nguyen Thanh Tu Collection
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...DhatriParmar
 
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...HetalPathak10
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
Comparative Literature in India by Amiya dev.pptx
Comparative Literature in India by Amiya dev.pptxComparative Literature in India by Amiya dev.pptx
Comparative Literature in India by Amiya dev.pptxAvaniJani1
 

Recently uploaded (20)

Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
 
Shark introduction Morphology and its behaviour characteristics
Shark introduction Morphology and its behaviour characteristicsShark introduction Morphology and its behaviour characteristics
Shark introduction Morphology and its behaviour characteristics
 
How to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineHow to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command Line
 
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of EngineeringFaculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
 
Objectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxObjectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptx
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
 
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFEPART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
 
DiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdfDiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdf
 
4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx
 
Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...
Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...
Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdf
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
Introduction to Research ,Need for research, Need for design of Experiments, ...
Introduction to Research ,Need for research, Need for design of Experiments, ...Introduction to Research ,Need for research, Need for design of Experiments, ...
Introduction to Research ,Need for research, Need for design of Experiments, ...
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
 
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
Comparative Literature in India by Amiya dev.pptx
Comparative Literature in India by Amiya dev.pptxComparative Literature in India by Amiya dev.pptx
Comparative Literature in India by Amiya dev.pptx
 

SQL and Database Fundamentals

  • 2. www.SunilOS.com 2 SQL It stands for Structured Query Language. Standardized syntax for “querying” (accessing) a relational database. It is assumed that SQL is database independent but there are important variations from Database to Database.
  • 3. www.SunilOS.com 3 Sales System Tables Order id date part_id qty 1 2/12/2006 1 100 2 3/15/2006 2 200 3 3/15/2006 3 100 4 4/5/2006 2 300 5 4/15/2006 3 200 6 6/15/2006 1 400 7 8/1/2006 1 100 Part id name color unit_id 1 Nut Grey 2 2 Bolt Grey 3 3 Screw Silver 2 Unit id city Capacity 1 New York 1000 2 London 2000 3 Paris 3000 Primary Key Foreign Key Foreign Key Primary Key
  • 4. www.SunilOS.com 4 SQL Statements  DDL data definition language o Statement for defining tables  Create & Alter Tables o Statement for deleting tables  Drop table  DML data manipulation language o Statement for Queries  SELECT * FROM part; o Statement for Inserting and Updating data  INSERT into part VALUES(4,'plat','Green',1);  UPDATE part SET color = 'Green', unit_id = 1 where id=4; o Statement for deleting rows  DELETE FROM part WHERE id=4;  DCL – Data Control Language o Commit : Saves data changes o Rollback : Reverts data changes o Savepoint : transaction demarcation.
  • 5. www.SunilOS.com 5 DDL Statements CREATE TABLE `part` ( `id` int(11) NOT NULL, `name` text, `color` text, `unit_id` int(11) default NULL, PRIMARY KEY (`id`) ) ALTER TABLE `part` ADD `color` text/
  • 6. www.SunilOS.com 6 DML Statements  Statement to insert all columns into part table. INSERT INTO part VALUES (4,'plat','Green',1);  Statement to insert id and name columns into part table. INSERT INTO part (id,name) VALUES (4,'plat');  Statement to update color and unit_id into part table. UPDATE part SET color = 'Green', unit_id = 1 WHERE id=4;  Statement to delete record from part table. DELETE FROM part WHERE id=4;
  • 7. www.SunilOS.com 7 DML - Select Get all parts o SELECT * FROM part; Get all parts’ ids, names and colors o SELECT id, name, color FROM part; Get all grey color parts o SELECT * FROM part WHERE color = ‘Grey’ Get all parts sorted by name o SELECT * FROM part ORDER BY name
  • 8. www.SunilOS.com 8 DML – Aggregate Functions How many parts are there? o SELECT count(*) from part; o SELECT count(id) from part; How many parts have been sold? o SELECT sum(qty) from order Which is the biggest deal so far? o SELECT max(qty) from order; Which is the minimum deal so far? o SELECT min(qty) from order;
  • 9. www.SunilOS.com 9 Joins  Get parts with their cities of units. o Columns :part.id, name, color, unit.city o Tables :part & unit o Condition :part.unit_id = unit.id;  SELECT part.id, name, color, unit.city FROM part, unit WHERE part.unit_id = unit.id;
  • 10. www.SunilOS.com 10 Aliases  SELECT p.id PartID, name, color, u.city FROM part p, unit u WHERE p.unit_id = u.id  Or  SELECT p.id as PartID, name, color, u.city FROM part as p, unit as u WHERE p.unit_id = u.id
  • 11. SQL IN/BETWEEN  Get the list of all Silver and Grey parts. o SELECT * FROM part WHERE color IN ('Grey','Silver')  Get orders those ordered quantities are between 100 to 200. o SELECT * from orders WHERE qty BETWEEN 100 AND 200  Get part counts for each color. o SELECT color, count (*) part FROM part GROUP BY color www.SunilOS.com 11
  • 12. www.SunilOS.com 12 Nested Query A Query can be nested in another query. Get part ids those are ordered more than 100. o SELECT part_id FROM orders WHERE qty > 100 Get part names those are ordered more than 100. o SELECT name FROM part o WHERE id IN o ( SELECT part_id FROM orders WHERE qty > 100)
  • 13. www.SunilOS.com 13 Joins Outer Join Inner Join Left Join Right Join
  • 14. Joins www.SunilOS.com 14 SELECT * from TableAA LEFT JOIN TableB B ON A.Key = B.Key SELECT * from TableAA RIGHT JOIN TableB B ON A.Key = B.Key SELECT * from TableAA OUTER JOIN TableB B ON A.Key = B.Key SELECT * from TableAA INNER JOIN TableB B ON A.Key = B.Key
  • 15. www.SunilOS.com 15 PDBC Overview Python Database Connectivity. Python supports various databases like MySQL, Oracle, Sybase etc. We can use Python DB-API for database connectivity. DB-API:- o pymysql for mysql database. o cx_Oracle for oracle database. o pymssql for msSQL database.
  • 16. www.SunilOS.com 16 MYSQL – Get Data  import pymysql  result=""  connection = pymysql.connect(host='localhost',user='root',password='root',db='test')  with connection.cursor() as cursor:  sql = "select * from part"  cursor.execute(sql)  result= cursor.fetchall()  connection.close()  for d in result:  print(d[0]," ",d[1],"t", d[2])  Column value by index SQL Query DB URL Login ID PWD
  • 17. www.SunilOS.com 17 Connect with Database Here are the steps to be followed to make a database call: 1. Import that database specific module. 2. Make connection to the Database 3. Create Cursor object 4. Execute cursor.fetchall and get Result or execute insert/update/delete query and get number of records affected Note:First Install pymysql by command o pip install pymysql
  • 18. www.SunilOS.com 18 MYSQL – Insert/Update Data  import pymysql  import traceback  try:  connection = pymysql.connect(host='localhost',user='root',password='root',db='test')  with connection.cursor() as cursor:  sql = "INSERT INTO part (`ID`,`NAME`,`COLOR`)VALUES (%s,%s,%s)"  try:  cursor.execute(sql, (5, 'screw', 'silver'))  connection.commit()  print("Data add successfully")  except Exception:  connection.rollback()  traceback.print_exc()  print("Oops! Something wrong")  finally:  connection.close() 
  • 19. www.SunilOS.com 19 Cursor Methods  cursor.fetchall() o Executes an SQL statement and returns a Result.  cursor.execute(String) o Executes an SQL INSERT, UPDATE or DELETE statement and returns the number of rows changed.
  • 20. www.SunilOS.com 20 PDBC URLs  ORACLE Import cx_Oracle Connection = cx_Oracle.connect(‘scott/tiger@localhost’)  MSSQL Import cx_Oracle Connection = cx_Oracle.connect(‘scott/tiger@localhost’)
  • 21. www.SunilOS.com 21 Stored Procedures It is written in database specific language. It is stored in database. It is accessed by callproc. o cursor.callproc(‘StoredProcedureName’)
  • 22. www.SunilOS.com 22 Call to a Stored Procedure  import pymysql  import traceback  connection = pymysql.connect(host='localhost',user='root',password='root',db='abc')  with connection.cursor() as cursor:  cursor.callproc(“userCount")  for result in cursor.fetchall():  print(result)  connection.close() 
  • 23. www.SunilOS.com 23 MYSQL – User Count DELIMITER $$ DROP PROCEDURE IF EXISTS `userCount`$$ CREATE PROCEDURE test.`userCount`() BEGIN SELECT COUNT(*) FROM users ; END$$ DELIMITER ;
  • 24. www.SunilOS.com 24 Transaction Handling  A transaction is a set of data changes made by multiple SQL statements. Entire changes of this set will be either committed (saved) or rolled back (reverted) together.  By default each statement is committed irrespective of others failures.  Transaction begins by: o conn.autocommit = false; o Default value of auto commit is true.  Transaction ends by calling: o connection.commit() o conncetion.rollback();
  • 25. www.SunilOS.com 25 Transaction Handling : Commit import pymysql Sql = "INSERT INTO company(`ID`,`NAME`,`ADDRESS`)VALUES (%s,%s,%s)" connection = pymysql.connect(host='localhost',user='root',password='root',db='abc') connection.autocommit = False with connection.cursor() as cursor: cursor.execute(sql, (109,‘NCS',‘Indore')) cursor.execute(sql1, (109,‘Rays',‘Indore')) connection.commit()
  • 26. www.SunilOS.com 26 Mapping Python Types to SQL Types SQL type Python Type CHAR, VARCHAR, LONGVARCHAR String NUMERIC, DECIMAL float BIT bool TINYINT int SMALLINT int INTEGER int BIGINT int REAL float FLOAT, DOUBLE float BINARY, VARBINARY, LONGVARBINARY byte.String DATE datetime.date TIME datetime.time TIMESTAMP datetime.datetime Date + Time (Nano sec)
  • 27. www.SunilOS.com 27 Database Time python defines datetime module to handle date and time:  datetime.date o year, month, day  datetime.time o hours, minutes, seconds, microseconds  datetime.datetime o year, month, day, hours, minutes, seconds, microseconds o By default Timestamp should be used
  • 28. www.SunilOS.com 28 Metadata – Data about Data  import pymysql  connection = pymysql.connect(host='localhost',user='root',password='root',db='abc')  with connection.cursor() as cursor:  cursor.execute("select * from company ")  cursor.fetchall()  meta=cursor.description  for data in meta:  print("t",data[0],end="")  connection.close() 
  • 29. www.SunilOS.com 29 Python Bean Marksheet -rollNo : String -name : String -chemistry : int -physics : int -maths:int +setters +getters
  • 30. www.SunilOS.com 30 DAO MarksheetDAO + add (Marksheet) + update (Marksheet) + delete (rollNo) : Marksheet + get (rollNo) : Marksheet +getMeritList(): ArrayList +search(Marksheet) TestMarksheetDAO + testAdd () + testUpdate () + testDelete () + testGet () +testGetMeritList() +testSearch()
  • 31. Disclaimer This is an educational presentation to enhance the skill of computer science students. This presentation is available for free to computer science students. Some internet images from different URLs are used in this presentation to simplify technical examples and correlate examples with the real world. We are grateful to owners of these URLs and pictures. www.SunilOS.com 31

Editor's Notes

  1. www.sunilos.com
  2. Cell- 98273 60504
  3. Cell- 98273 60504
  4. Cell- 98273 60504
  5. Cell- 98273 60504
  6. Cell- 98273 60504
  7. Cell- 98273 60504
  8. Cell- 98273 60504
  9. Cell- 98273 60504
  10. Cell- 98273 60504
  11. Cell- 98273 60504
  12. Cell- 98273 60504
  13. Cell- 98273 60504
  14. Cell- 98273 60504
  15. Cell- 98273 60504
  16. Cell- 98273 60504
  17. Cell- 98273 60504
  18. Cell- 98273 60504
  19. Cell- 98273 60504
  20. Cell- 98273 60504
  21. Cell- 98273 60504
  22. Cell- 98273 60504
  23. Cell- 98273 60504
  24. Cell- 98273 60504
  25. Cell- 98273 60504
  26. Cell- 98273 60504
  27. Cell- 98273 60504
  28. Cell- 98273 60504
  29. Cell- 98273 60504