0% found this document useful (0 votes)
682 views31 pages

Computer Science Class 12 - SQL

This document provides information on database management systems and structured query language (SQL). It discusses that a DBMS allows for the storage, retrieval, and management of data in a database. It notes some disadvantages of file processing systems that prompted the development of DBMS. It then describes key aspects of databases, schemas, SQL, and different SQL commands. In particular, it summarizes that SQL is a language used to define, manipulate, and retrieve data from relational databases and includes commands to create, read, update, and delete data as well as database structures.

Uploaded by

gopishukla0103
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
682 views31 pages

Computer Science Class 12 - SQL

This document provides information on database management systems and structured query language (SQL). It discusses that a DBMS allows for the storage, retrieval, and management of data in a database. It notes some disadvantages of file processing systems that prompted the development of DBMS. It then describes key aspects of databases, schemas, SQL, and different SQL commands. In particular, it summarizes that SQL is a language used to define, manipulate, and retrieve data from relational databases and includes commands to create, read, update, and delete data as well as database structures.

Uploaded by

gopishukla0103
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 31

3

2
-
2
2
0
2
DBMS-DATABASE MANAGEMENT SYSTEM
DBMS:
A database management system (DBMS) is a collection of interrelated data and a set of
programs to access those data. The collection of data, usually referred to as the
database, contains information relevant to an enterprise. The DBMS provides a way to
store and retrieve database information that is both convenient and efficient.
Keeping organizational information in a file- processing system has a number of major
disadvantages like:
a) Data redundancy and inconsistency
b) Difficulty in accessing data
c) Data isolation
d) Integrity problems
e) Atomicity problems
f) Concurrent access anomalies
g) Security problems
These difficulties among others, prompted the development of database systems.
● Database systems are designed to manage large bodies of information.
● Management of data involves both defining structures for storage of information
and providing mechanisms for the manipulation of information.
● The database system also must ensure the safety of the information stored,
despite system crashes or attempts at unauthorized access. If data are to be
shared among several users, the system must avoid possible anomalous results.
● DBMS lets users to create a database, store, manage, update/modify and retrieve
data from that database by users or application programs.
Some examples of open source and commercial DBMS include MySQL, Oracle,
PostgreSQL, SQL Server, Microsoft Access, MongoDB.
Database systems are widely used. Some representative applications are :
a) Banking
b) Airlines
c) Universities
d) Telecommunications
e) Sales
f) Finance, etc.
A data model describes the structure of the database, including how data are defined
and represented, relationships among data, and the constraints.
Database schema: Database Schema is the design of a database. It is the skeleton of the
database that represents the structure (table names and their fields/columns), the type
of data each column can hold, constraints on the data to be stored (if any), and the
relationships among the tables.
Database schema is also called the visual or logical architecture as it tells us how the data
are organized in a database.
Data constraint: Restrictions or limitations are put on the type of data that can be inserted
in one or more columns of a table to ensure accuracy and reliability of data in the
database.
Meta – Data or Dictionary: A database catalog or dictionary that has data about data.
Database instance: The state of database at any time, after loading of data. A database
schema can have different instances at different times.
Query: A query is a request to a database for obtaining information in a desired way.
Data Manipulation: Modification of database consists of three operations viz. Insertion,
Deletion or Update.
Database engine: Database engine is the underlying component or set of programs used
by a DBMS to create database and handle various queries for data retrieval and
manipulation.

Relational model:
The relational model uses a collection of tables to represent both data and the
relationships among those data.
Each table has multiple columns, and each column has a unique name. The relational
model is an example of a record – based model.
Record- based models are so named because the database is structured in fixed- format
records of several types. Each table contains records of particular type. Each record type
defines a fixed number of fields/attributes.
The columns of the table correspond to the attributes of the record type.
A row in a table represents a relationship among a set of values. The relational data model
is the most widely used data model.
Other types of data models include object-oriented data model, entity-relationship data
model, document model and hierarchical data model.

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 175
Relation: A Relation is logically related data organized in the form of tables.
Attribute/ Field: Column of a table is called Attribute or Field.
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.

Primary Key – A primary is a column or set of columns in a table that uniquely


identifies tuples (rows) in that table.

Candidate Key –It is an attribute or a set of attributes or keys participating for Primary
Key, to uniquely identify each record in that table.

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.
STRUCTURED QUERY LANGUAGE(SQL)
Structured Query Language: introduction, Data Definition Language and Data
Manipulation Language, data type (char(n), varchar(n), int, float, date), constraints
(not null, unique, primary key), create database, use database, show databases,
drop database, show tables, create table, describe table.

1.1 What is SQL?


SQL(Structured Query Language) is a language that is used to manage data that is
held in a relational database management system. It uses tables to manipulate and
retrieve information from databases for analysis.
By using SQL commands, one can search for any data in the database and
perform other functions like creating tables, adding records, modifying data, removing
rows, dropping tables etc.
1.2 What Can SQL do?
SQL can execute queries against a database
SQL can retrieve data from a database
SQL can insert records in a database
SQL can update records in a database
SQL can delete records from a database
SQL can create new databases
SQL can create new tables in a database
SQL can create stored procedures in a database
SQL can create views in a database
SQL can set permissions on tables, procedures, and views
1.3 ADVANTAGES OF SQL
There are the following advantages of SQL:
● High speed
Using the SQL queries, the user can quickly and efficiently retrieve a large amount of
records from a database.
● No coding needed
In the standard SQL, it is very easy to manage the database system. It doesn't require a
substantial amount of code to manage the database system.
● Well defined standards
Long established are used by the SQL databases that are being used by ISO and ANSI.
● Portability
SQL can be used in laptop, PCs, server and even some mobile phones.
● Interactive language
SQL is a domain language used to communicate with the database. It is also used to
receive answers to the complex questions in seconds.
● Multiple data view
Using the SQL language, the users can make different views of the database structure

1.4 SQL Commands


SQL commands are instructions. It is used to communicate with the database. It is also
used to perform specific tasks, functions, and queries of data.
SQL can perform various tasks like create a table, add data to tables, drop the table, modify
the table, set permission for users.

1.5 Types of SQL Commands


There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.

1.5.1 DDL or Data Definition Language


DDL or Data Definition Language actually consists of the SQL commands that can be used
to define the database schema. It simply deals with descriptions of the database schema
and is used to create and modify the structure of database objects in the database. DDL is
a set of SQL commands used to create, modify, and delete database structures but not
data.

List of DDL commands:


CREATE: This command is used to create the database or its objects (like table,
index, function, views, store procedure, and triggers).
DROP: This command is used to delete objects from the database.
ALTER: This is used to alter the structure of the database.
TRUNCATE: This is used to remove all records from a table, including all spaces
allocated for the records are removed.
COMMENT: This is used to add comments to the data dictionary.
RENAME: This is used to rename an object existing in the database.

1.5.2 DML (Data Manipulation Language):


The SQL commands that deals with the manipulation of data present in the database
belong to DML or Data Manipulation Language and this includes most of the SQL
statements. It is the component of the SQL statement that controls access to data and to
the database. Basically, DCL statements are grouped with DML statements.
List of DML commands:
INSERT : It is used to insert data into a table.
UPDATE: It is used to update existing data within a table.
DELETE : It is used to delete records from a database table.
Difference between DDL and DML:
DDL DML
It stands for Data Definition It stands for Data
Language. Manipulation Language.

It is used to create database


schema and can be used to
define some constraints as It is used to add, retrieve or
well. update the data.

It basically defines the It add or update the row of


column (Attributes) of the the table. These rows are
table. called as tuple.
1.6 DATATYPES

⮚ Text Data types


Char(size) – fixed length of size bytes
Varchar(size)-variable length of size bytes
Varchar2(size)-variable length of size bytes

⮚ Number Data types


Integer(size)or Int- It represents a number without decimal point
Float(Size)-It represents a floating point number
Real-Same as float but no size argument is used

➢ Date data type


Date , Time
1.7 CONSTRAINT
A Constraint is a condition or check applicable on a field or set of fields.
Types of Constraints:

⮚ Unique Constraint :-This ensures that no rows have the same value in the
specified column(s)
Syntax:
Create table EMP (ecode integer unique, ename char(20),sex char(1),grade
char(2));
Unique constraint applied on ecode of EMP table ensures that no rows have the same
ecode value

⮚ Primary key Constraint:- This declares a column as the primary key of the table
This is similar to unique constraint except that one column (or one group of
columns)can be applied in this constraint .
The primary key cannot allow NULL values but Unique key allows NULL values.
The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons" table
is created:
CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL,
FirstName varchar(255), Age int, PRIMARY KEY (ID));

⮚ Not null:-This constraint ensures column should not be NULL


Syntax:
Create table EMP(ecode integer Not null unique, ename char(20),sex char(1),grade
char(2));

1.8 DATABASE COMMANDS IN MYSQL


⮚ CREATE DATABASE
CREATE DATABASE is the SQL command used for creating a database in MySQL.
Imagine you need to create a database with name “movies”. You can create a database
in MySQL by executing following SQL command
Syntax: mysql>CREATE DATABASE movies;

⮚ SHOW DATABASES
You can see list of existing databases by running following SQL command.
Syntax: mysql>SHOW DATABASES;

⮚ USE
You can use SQL command USE to select a particular database.
Syntax: mysql>USE database_name;

⮚ DROP DATABASE
The DROP DATABASE statement is used to drop an existing SQL database.
Syntax :mysql>DROP DATABASE database_name;

CREATE TABLE
The CREATE TABLE statement is used to create a new table in a database.
Syntax: CREATE TABLE table_name ( column1 datatype, column2
datatype, column3 datatype, ...... );
Example: The following example creates a table called "Persons" that contains five
columns:
PersonID, LastName, FirstName, Address, and City:
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

⮚ SHOW TABLES;
We can get the number of table information of a database using the following
statement:
mysql> SHOW TABLES;

⮚ DESCRIBE TABLE
Use the DESCRIBE command to show the structure of the table, such as column names,
constraints on column names, etc. The DESC command is a short form of the DESCRIBE
command. Both DESCRIBE and DESC commands are equivalent.
Syntax The following are the syntax to display the table structure:
mysql> DESCRIBE | DESC table_name;

ALTER TABLE Statement


The ALTER TABLE statement is used to add, delete, or modify columns in an existing
table.The ALTER TABLE statement is also used to add and drop various constraints on an
existing table.

ALTER TABLE - ADD Column/Attribute To add a column in a table, use the following
syntax:

ALTER TABLE table_name ADD column_name datatype;

Example ALTER TABLE Customers ADD Email varchar(255);

ALTER TABLE - DROP COLUMN

To delete a column in a table, use the following syntax

ALTER TABLE table_name DROP COLUMN column_name;

Example ALTER TABLE Customers DROP COLUMN Email;

SQL PRIMARY KEY on ALTER TABLE

To create a PRIMARY KEY constraint on the "ID" column when the table is already
created, use the following SQL:
ALTER TABLE table_name ADD PRIMARY KEY (Column_name);

Example ALTER TABLE Persons ADD PRIMARY KEY (ID);

DROP a PRIMARY KEY Constraint

To drop a PRIMARY KEY constraint, use the following SQL:

ALTER TABLE table_name DROP PRIMARY KEY;

Example : ALTER TABLE Persons DROP PRIMARY KEY;

The SQL DROP TABLE Statement


The DROP TABLE statement is used to drop an existing table in a database.

Syntax DROP TABLE table_name;

DROP TABLE Shippers;

INSERT INTO Statement:


The INSERT INTO statement is used to insert new records in a table.

INSERT INTO Syntax:

It is possible to write the INSERT INTO statement in two ways:

1. Specify both the column names and the values to be inserted:

INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2,
value3, ...);

2. If you are adding values for all the columns of the table, you do not need to specify
the column names in the SQL query. However, make sure the order of the values is in
the same order as the columns in the table. Here, the INSERT INTO syntax would be as
follows:

INSERT INTO table_name VALUES (value1, value2, value3, ...);

The SQL DELETE Statement:


The DELETE statement is used to delete existing records in a table.

DELETE Syntax:
DELETE FROM table_name WHERE condition;

Note: Be careful when deleting records in a table! Notice the WHERE clause in the
DELETE statement. The WHERE clause specifies which record(s) should be deleted. If you
omit the WHERE clause, all records in the table will be deleted!

The following SQL statement deletes all rows in the "Customers" table, without deleting
the table:

DELETE FROM Customers;

The SQL SELECT Statement

The SELECT statement is used to select data from a database.

The data returned is stored in a result table, called the result-set.

SELECT Syntax: SELECT column1, column2, ... FROM table_name;

Here, column1, column2, ... are the field names of the table you want to select data
from. If you want to select all the fields available in the table, use the following syntax:

SELECT * FROM table_name;

The SQL WHERE Clause:


The WHERE clause is used to filter records.

It is used to extract only those records that fulfill a specified condition.

WHERE Syntax: SELECT column1, column2, ...FROM table_name WHERE condition;

Operators in The WHERE Clause

The following operators can be used in the WHERE clause:

Operator Description

= Equal

> Greater than

< Less than

>= Greater than or equal


<= Less than or equal

<> Not equal. Note: In some versions of SQL this


operator may be written as !=

BETWEEN Between a certain range

LIKE Search for a pattern

IN To specify multiple possible values for a


column

The SQL AND, OR and NOT Operators

The WHERE clause can be combined with AND, OR, and NOT operators.

The AND and OR operators are used to filter records based on more than one condition:

● The AND operator displays a record if all the conditions separated by AND are TRUE.
● The OR operator displays a record if any of the conditions separated by OR is TRUE.

The NOT operator displays a record if the condition(s) is NOT TRUE.

AND Syntax

SELECT column1, column2, ...

FROM table_name

WHERE condition1 AND condition2 AND condition3 ...;

OR Syntax

SELECT column1, column2, ...

FROM table_name

WHERE condition1 OR condition2 OR condition3 ...;

NOT Syntax

SELECT column1, column2, ...

FROM table_name

WHERE NOT condition;


The SQL IN Operator

The IN operator allows you to specify multiple values in a WHERE clause.

The IN operator is a shorthand for multiple OR conditions.

IN Syntax

SELECT column_name(s)

FROM table_name

WHERE column_name IN (value1, value2, ...);

or:

SELECT column_name(s)

FROM table_name

WHERE column_name IN (SELECT STATEMENT);

The SQL BETWEEN Operator

The BETWEEN operator selects values within a given range. The values can be numbers,
text, or dates.

The BETWEEN operator is inclusive: begin and end values are included.

BETWEEN Syntax

SELECT column_name(s)

FROM table_name

WHERE column_name BETWEEN value1 AND value2;

The SQL ORDER BY Keyword

The ORDER BY keyword is used to sort the result-set in ascending or descending order.

The ORDER BY keyword sorts the records in ascending order by default. To sort the
records in descending order, use the DESC keyword.
ORDER BY Syntax

SELECT column1, column2, ...

FROM table_name

ORDER BY column1, column2, ... ASC|DESC;

Example

SELECT * FROM Customers

ORDER BY Country;

ORDER BY DESC Example

The following SQL statement selects all customers from the "Customers" table, sorted
DESCENDING by the "Country" column:

SELECT * FROM Customers

ORDER BY Country DESC;

ORDER BY Several Columns Example

The following SQL statement selects all customers from the "Customers" table, sorted by
the "Country" and the "CustomerName" column. This means that it orders by Country,
but if some rows have the same Country, it orders them by CustomerName:

Eg: SELECT * FROM Customers ORDER BY Country, CustomerName;

SQL Aliases

SQL aliases are used to give a table, or a column in a table, a temporary name.

Aliases are often used to make column names more readable.

An alias only exists for the duration of that query.

An alias is created with the AS keyword.

Alias Column Syntax: SELECT column_name AS alias_name FROM table_name;

Alias Table

Syntax: SELECT column_name(s) FROM table_name AS alias_name;


The SQL UPDATE Statement

The UPDATE statement is used to modify the existing records in a table.

UPDATE Syntax: UPDATE table_name SET column1 = value1, column2 = value2, ...

WHERE condition;

UPDATE Table

The following SQL statement updates the first customer (CustomerID = 1) with a new
contact person and a new city.

UPDATE Customers

SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'

WHERE CustomerID = 1;

The SQL SELECT DISTINCT Statement

The SELECT DISTINCT statement is used to return only distinct (different) values.

Inside a table, a column often contains many duplicate values; and sometimes you only
want to list the different (distinct) values.

SELECT DISTINCT Syntax:

SELECT DISTINCT column1, column2, ...FROM table_name;

SELECT Example Without DISTINCT

The following SQL statement selects all (including the duplicates) values from the
"Country" column in the "Customers" table:

Eg: SELECT Country FROM Customers;

Now, let us use the SELECT DISTINCT statement

and see the result.

SELECT DISTINCT Examples

The following SQL statement selects only the DISTINCT values from the "Country"
column in the "Customers" table:
SELECT DISTINCT Country FROM Customers;

The following SQL statement lists the number of different (distinct) customer countries:

SELECT COUNT(DISTINCT Country) FROM Customers;

The SQL LIKE Operator

The LIKE operator is used in a WHERE clause to search for a specified pattern in a
column.

There are two wildcards often used in conjunction with the LIKE operator:

● The percent sign (%) represents zero, one, or multiple characters


● The underscore sign (_) represents one, single character

The percent sign and the underscore can also be used in combinations!

LIKE Syntax

SELECT column1, column2, ...

FROM table_name

WHERE columnN LIKE pattern;

LIKE Operator Description

WHERE CustomerName LIKE 'a%' Finds any values that start with "a"

WHERE CustomerName LIKE '%a' Finds any values that end with "a"

WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position

WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second
position

WHERE CustomerName LIKE 'a_%' Finds any values that start with "a" and are at
least 2 characters in length

WHERE CustomerName LIKE 'a %' Finds any values that start with "a" and are at
least 3 characters in length

WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and ends with
"o"
What is a NULL Value?

A field with a NULL value is a field with no value.

If a field in a table is optional, it is possible to insert a new record or update a record


without adding a value to this field. Then, the field will be saved with a NULL value.

How to Test for NULL Values?

It is not possible to test for NULL values with comparison operators, such as =, <, or <>.

We will have to use the IS NULL and IS NOT NULL operators instead.

IS NULL Syntax

SELECT column_names

FROM table_name

WHERE column_name IS NULL;

IS NOT NULL Syntax

SELECT column_names

FROM table_name

WHERE column_name IS NOT NULL;

The IS NULL Operator

The IS NULL operator is used to test for empty values (NULL values).

The following SQL lists all customers with a NULL value in the "Address" field:

SELECT CustomerName, ContactName, Address

FROM Customers

WHERE Address IS NULL;

The IS NOT NULL Operator

The IS NOT NULL operator is used to test for non-empty values (NOT NULL values).

The following SQL lists all customers with a value in the "Address" field:
SELECT CustomerName, ContactName, Address

FROM Customers

WHERE Address IS NOT NULL;

Aggregate (Group) function


● Aggregate functions are the functions that operate on a set of rows to give one
result per group.
● These sets of rows on which group function is applied may be the whole table or
the table split into groups.
Types of Group Functions

Function Description

sum() Find the sum of numeric values

avg() Find the average of numeric values

count() Counts the number of rows in a table

max() Find the maximum among all the values in a column

min() Find the minimum among all the values in a column


Remember the following points about group functions:
● All group functions,except count(*) ignore NULL values
● Functions -sum(),avg() are used with NUMERIC data.
● Functions -min() and max() can be used with any data type
Example:
Consider the following table employee
Q: Find the sum, average, minimum, maximum value of salaries of employees in the
employee table

Count() function
Count () has got three formats:
Count(*)
This function returns the number of rows in the table that satisfy the criteria of select
statement.
In its counting, it includes duplicate rows and rows with NULL values in any of the
column
Example:
Q: Count the number of employees in the employee table.

Count(<col name>)
● This function returns the number of not null values in the specified column, but
includes duplicate values in counting
Example
Q; count the number of grades of employees in the employee table.

Count(DISTINCT <col name>)


This function returns the number of unique, not null values in the specified column.
Example
Q Count the number of different grades of the employee

Grouping Records (Group by clause)

 To divide the rows in a table into smaller groups of information, group by clause
is used.
 It combines all identical rows in a group of fields.
 A column name is used for grouping
Syntax;-
SELECT [DISTINCT] <COL LIST> FROM <TABLE NAME>
[WHERE <CONDITION>]
[GROUP BY < GROUP BY EXPR>]
[HAVING <CONDITION>]
[ORDER BY <COL NAME>/<EXPR> ASC/DESC];
NOTE -
● Group by expression specifies the columns whose values determine the basics for
grouping rows
● WHERE clause is always before GROUP BY if required.
Example
Q. Display the no of employees in each zone.

Q. Display the no of employees in each zone whose salary is greater than 32000
Having clause
● This clause is used to restrict rows resulting after grouping.
● Steps followed in execution of select with group by and having clause-
1. Rows are grouped according to the columns in the group by clause.
2. Then the group function is applied.
3. Groups matching with Having clauses are displayed.
Example
Q. Display only whose departments with sum of salaries whose total salary is greater
than 70000

Cartesian Product (Cross Join or unrestricted join)


 Returns all the rows in the two tables listed in the query.
 Each row of the first table is paired with all the rows in the second table.
 This happens when there is no relationship between two tables.
 It is rarely useful.

Example- Consider the following tables


Q: To display the name of the employees and their department name

Joins in MySQL
● A join is used when data from two or more tables is required.
● Rows in one table can be joined to the rows in another table based on the
common values existing in corresponding columns of two tables.
● Joins are used to retrieve data from tables related to each other with primary-
foreign key relationships.
● There are many types of join
Equi join
● Specified columns from the joining tables are checked for equality.
● Values from joining tables are retrieved only if the condition in where clause is
satisfied.
SYNTAX:-
SELECT <column_name (s)>
FROM <table_name1>, <table_name2>, .... , <table_nameN>
WHERE <table_name1>.<column_name> = <table_name2>.<column_name>;

Q: to display the name of the employee and their department


Note-
To join n tables together minimum of n-1 join conditions are to be satisfied.
Results of Equi joins are the same as simple joins or inner joins. Inner join (simply join)
uses on clause.
You should always qualify the columns when joining tables having the same name as
corresponding columns. To qualify the columns we use “.” (dot) operator.

Natural Join
This clause is based on all the columns in the two tables that have the same name.
It selects the rows from two tables that have equal values in the matched columns.
SYNTAX:-

SELECT [column_names | *]
FROM table_name1
NATURAL JOIN table_name2;

Example- consider the same tables employee and department.


Q : To display the name of employee and department of all employee

Note-No need to specify the column names to join. Works with same column name in
both the tables. The Resulting table has unique columns.
Interface Python with SQL database
Contents:
 Connecting SQL with Python
 Creating database connectivity applications
 Performing insert, delete, update,delete queries
 Display data by using fetchone(), fetchall(), fetchmany (),
rowcount()

Database connectivity
Database connectivity refers to connection and communication between an application
and a database system.
The term “front-end” refers to the user interface, while “back-end” means the server,
application and database that work behind the scenes to deliver information to the user.
 Mysql.connector- Library or package to connect from python to MySQL.

Before we connect the program with mysql , we need to install connectivity package named
mysql-connector- python
 Command to install connectivity package:- pip install mysql-connector-python
 Command to import connector:- import mysql.connector
 Steps for python MySQL connectivity

1 . Install Python
2. Install MySQL
3. Open Command prompt
4. Switch on internet connection
5. Type pip install mysql-connector-python and execute
6. Open python IDLE
7. import mysql.connector

Steps for creating database connectivity applications:

1. Start Python- start python editor to create our own python script.

2. Import mysql.connector package

Use the following statement for this.


import mysql.connector or

import mysql.connector as Con

3. Establishing a connection to Mysql DATABASE.

We need to establish a connection to a mysql database using connect () function of


mysql.connector package.

The connect statement creates a connection to the mysql server and returns a
MySQL connection object.

Syntax:

<Connection object> = mysql.connector.connect (host=<hostname>,


user=<username>, passwd:<password>, database=<dbname>)

For eg: import mysql.connector

con=mysql.connector.connect(host=”localhost”,user=”root”, passwd=” “)

4. Creating a cursor Object

It is a useful control structure of database connectivity. It will let us execute


all the queries we need. Cursor stores all the data as a temporary container of
returned data and allows traversal so that we can fetch data one row at a time
from cursor. Cursors are created by the connection.cursor() method.

Syntax:

<cursor object>=<connectionobject>.cursor()

Eg: cursor=con.cursor()

5. Execute SQL query:

We can execute SQL query using execute() function .

Syntax: <cursor object>.execute(SQL QUERY)

Eg: cursor.execute(“select * from data”)

The above code will execute the sql query and store the retrieved records
(resultset) in the cursor object(cursor).
Result set refers to a logical set of records that are fetched from the database
by executing an sql query and made available in the program.

6. Extract data from Result set:

The records retrieved from the database using SQL select query has to be
extracted as record from the result set. We can extract data from the result set
using the following fetch () function.

fetchall()

fetchone()

fetchmany()

 Multiple ways to retrieve data:


 fetchall()- Fetches all (remaining) rows of a query result,
returning them as a sequence of sequences (e.g. a list of
tuples) .
 fetchone()-Fetches the next row of a query result set, returning
a single sequence or None when no more data is available
 fetchmany (size)-Fetches the next set of rows of a query
result, returning a sequence of sequences. It will return
number of rows that matches to the size argument.

Functions to execute SQL queries

# TO CREATE DATABASE SCHOOL USING PYTHON INTERFACE

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system
")
mycursor=mydb.cursor()
mycursor.execute("CREATE DATABASE SCHOOL")

# SHOW DATABASE

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system")
mycursor=mydb.cursor()
mycursor.execute("SHOW DATABASES")
for x in mycursor:
print (x)

# TO CREATE A TABLE IN MYSQL USING PYTHON INTERFACE

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="s
ystem",database="student")
mycursor=mydb.cursor()
mycursor.execute("CREATE TABLE FEES (ROLLNO INT,NAME
VARCHAR(20),AMOUNT INT);")

# TO SHOW THE TABLES IN MYSQL USING PYTHON INTERFACE

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system
",database="student")
mycursor=mydb.cursor()
mycursor.execute("SHOW TABLES")
for x in mycursor:
print(x)
#TO DESCRIBE TABLE STRUCTURE USING PYTHON INTERFACE

mydb=mysql.connector.connect(host="localhost",user="root",passwd="system"
,database="student")
mycursor=mydb.cursor()
mycursor.execute("DESC STUDENT")
for x in mycursor:
print(x)
# TO EXECUTE SELECT QUERY USING A PYTHON INTERFACE

import mysql.connector
conn=mysql.connector.connect(host="localhost",user="root",passwd="12345
",database="student")
c=conn.cursor()
c.execute("select * from student")
r=c.fetchone()
while r is not None:
print(r)
r=c.fetchone()

# TO EXECUTE SELECT QUERY WITH WHERE CLAUSE USING A PYTHON INTERFACE


import mysql.connector
conn=mysql.connector.connect(host="localhost",user="root",passwd="12345",
database="student")
if conn.is_connected()==False:
print("Error connecting to MYSQL DATABASE")
c=conn.cursor()
c.execute("select * from student where marks>90")
r=c.fetchall()
count=c.rowcount
print("total no of rows:",count)
for row in r:
print(row)
#TO INSERT A RECORD (ROLLNO,NAME,AND MARKS) IN MYSQL TABLE student USING
#PYTHON INTERFACE
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system
",database="student") mycursor=mydb.cursor()
r=int(input("enter the rollno"))
n=input("enter name")
m=int(input("enter marks"))
mycursor.execute("INSERT INTO student(rollno,name,marks)
VALUES({},'{}',{})".format(r,n,m))
mydb.commit()
print(mycursor.rowcount,"RECORD INSERTED")

# TO UPDATE A DATA IN A TABLE USING PYTHON INTERFACE


import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="syste
m",database="student") mycursor=mydb.cursor()
mycursor.execute("UPDATE STUDENT SET MARKS=100 WHERE MARKS=40")
mydb.commit()
print(mycursor.rowcount,"RECORD UPDATED")
# TO DELETE A RECORD FROM THE TABLE USING PYTHON INTERFACE
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system
",database="student")
mycursor=mydb.cursor()
mycursor.execute("DELETE FROM STUDENT WHERE MARKS<50")
mydb.commit()
print(mycursor.rowcount,"RECORD DELETED")

# TO DROP AN ENTIRE TABLE FROM MYSQL DATABASE USING PYTHON INTERFACE


import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system
",database="student")
mycursor=mydb.cursor()
mycursor.execute("DROP TABLE STUDENT")

# TO ADD A COLUMN IN THE EXISTING TABLE USING PYTHON INTERFACE


import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system
",database="student")
mycursor=mydb.cursor()
mycursor.execute("ALTER TABLE STUDENT ADD AGE INT”)
mydb.commit()

#TO DROP A COLUMN FROM THE TABLE USING PYTHON INTERFACE


import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system
",database="student")
mycursor=mydb.cursor()
mycursor.execute("ALTER TABLE DROP AGE ”)
mydb.commit()

# TO ALTER THE DATATYPE OF A COLUMN IN A TABLE USING PYTHON INTERFACE

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="syste
m",database="student")
mycursor=mydb.cursor()
mycursor.execute("ALTER TABLE STUDENT MODIFY GRADE CHAR(3)")
 commit( ): After executing insert or update query we must commit our
transaction using commit method of connection object.
Eg: mycon.commit()
 rollback( ): mysqlConnection.rollback() reverts the changes made by the
current transaction.
 rowcount: This attribute returns the number of rows that were affected
by an execute()

Closing cursor and connection


Since the database can keep limited number of connections at a time ,
we must close the connection using
cursorobject.close()
Eg: mycursor.close()
con.close()

You might also like