0% found this document useful (0 votes)
37 views36 pages

Ip File Library Stock

Python was developed by Guido Van Rossum in 1991 and offers advantages like being easy to use, expressive, and having a complete cross-platform free and open source environment. It has some disadvantages like not being the fastest and having fewer libraries than languages like C, Java, and Perl. Popular Python distributions include Python and Anaconda, while popular IDEs are Python IDLE, Spyder IDE, JupyterNotes, and PyCharm IDE. Python supports dynamic typing and uses tokens like keywords, identifiers, values, punctuators, operators, and comments. Common data structures in Python include lists, dictionaries, and tuples. Pandas is a popular Python library used for data analysis and its main data structures are Series and DataFrame.

Uploaded by

anmkatariya2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views36 pages

Ip File Library Stock

Python was developed by Guido Van Rossum in 1991 and offers advantages like being easy to use, expressive, and having a complete cross-platform free and open source environment. It has some disadvantages like not being the fastest and having fewer libraries than languages like C, Java, and Perl. Popular Python distributions include Python and Anaconda, while popular IDEs are Python IDLE, Spyder IDE, JupyterNotes, and PyCharm IDE. Python supports dynamic typing and uses tokens like keywords, identifiers, values, punctuators, operators, and comments. Common data structures in Python include lists, dictionaries, and tuples. Pandas is a popular Python library used for data analysis and its main data structures are Series and DataFrame.

Uploaded by

anmkatariya2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

I. I.

CONTENT:-

I.INTRODUCTION TO PYTHON:
• Python was developed by Guido Van Rossum in February 1991.

• Python offers following advantages :

easy to use expressive

completecross-

platform free and open source

• Python offers following disadvantages :

not the fastest

lesser libraries than C,

Java, Perlnot strong on

type-binding

• In python, one can work in two different ways:

i) Interactive mode ii) Script mode

• Popular Python distributions are Python (default), Anaconda distribution etc.

• Popular Python IDEs are Python IDLE, Spyder IDE,

JupyterNotes, Pycharm IDE etc.

• Interactive mode does not save commands in form of a program and also,
output is sandwiched between commands.

• Interactive mode is suitable for testing code.

• Script mode is useful for creating programs and then run the programs later and get
complete output

• Python is an interpreted language.

• Python's interactive interpreter is also called Python Shell.

• A token is the smallest individual unit in a program.

• Python have tokens like:

1. Keywords 2. Identifiers(names)

3. Values(literals) 4. Punctuators

5. Operators 6. Comments

• A keyword is a reserved word carrying special meaning and purpose.

• Identifiers are the user-defined names for different parts of the program.
• In Python, an identifier may contain letters (a-z, A-Z), digits (0-9) and a symbol underscore(_).

• Literals are fixed values.

• String literal, numeric(integer, floating point literals, Boolean literals, special literal None).

• Operators are tokens that trigger some computation.

• Punctuators are symbol used to organize programming-sentence structures.

• A Python program can contain various components like expressions,


statements, comments,functions, blocks and indentation.

• An expression is a legal combination of symbols that represents a value.

• A statement is a programming instruction.

• In Python, comments begin with a # character.

• Function is a named code.

• A block is a group of statements.

• Blocks are represented through indentation.

• Python supports dynamic typing.

• The input() is used to obtain input from user.

• Output is generated through print() statement.

• Immutable types in Python mean that their values can't be changed in place.

• Mutable types means changeable values.

• 3 Mutable types: lists, dictionaries & sets.

• Different Operators:

Arithmetic operators Addition

operatorsRelational operators

Bitwise

operators Identify operators

Logical

operators

• Debugging refers to the process of locating the place of error, cause of error, and
correcting the codeaccordingly.

• Compile-time errors - grammatical mistakes.

• related to programming language.

• Runtime error - execution problem.

• Logical error - analytical mistake.


• Python statements: empty st., single st, & compound st.

• An empty statement does nothing

• Single statement forms a simple statement.

• A compound st. (group of statements) execute as a unit.

• If statement, while statement etc are compound statements.

• The iteration (looping) constructs mean repetition of statements. eg- If.else and if.elif.else

• The if-else st. can be nested i.e., an if st. can have another if st.

• The range() func. generates a sequence of list type.

• Most commonly used counting loop in Python is for loop.

 List:
• Python lists are mutable.

• Python will not create a fresh list when you make changes to an element of a list.

• Strings and tuples are immutable.

• To create a list, put a no. of comma-separated expressions in square brackets.

•[] - means an empty list

• Lists index their elements just like strings.

• Lists are stored in memory exactly like strings.

• Function len(L) returns the no. of items (count) in the list L.

• The + operator adds one list to the end of another.

• List slice is an extracted part of a list.

• Common list manipulation functions are: append(), insert(), extend(), sort(),


remove(), reverse(),pop(), max(), min(),sum()…

 Dictionaries:
• Dict. Are mutable with elements in the form of a key:value pair that associate keys to values.

• The keys of a Dict. Must be of immutable types.

• Dict. Are also called associative arrays or mapping or hashes.

• In Python dict., the elements(key:value pairs) are unordered

• Keys of a Dict. must be unique.


• Dict. can be created through {} and through dict() constructor.

• In Dict. the updation and addition of elements are similar in syntax.

• To delete an element, you can either use del statement or clear() method.

• Imp. Functions - len(), clear, get(), items(), keys(), values(), update(), setdefault(), sorted(),

• Min(), max(), sum() etc.

 Tuples:
• Tuples as those lists which can t be changed.

• Tuples are immutable.

• Represented as group of comma-separated values.

• It uses parentheses ()

• Python data types strings, lists, tuples, dictionary etc. are all iterables.

• Iterable is any Python object return its members, one at a time.

 Python Pandas:
• Pandas is Python's library for data analysis.

• Pandas has derived its name from "panel data system".

• The main author of Pandas is Wes McKinney.

• It is an open source, BSD library, offers high-performance, easy-to-use data


structure and dataanalysis tools.

• It can either on the shell prompt or in your script file (.py) by writing:

- Import pandas as pd

• It can read or write in many diff data formats.

• It can cal. in all the possible ways data is organized.

• It can easily select subsets of data.

• It allows you to apply operations.

• It supports reshaping of data into diff. forms.

• It supports advanced time-series functionality.

• It supports visualization by integrating matplotlib and seaborn etc. libraries.


• Data Structure refer to specialized way of storing data so as to apply a specific
type of functionalityon them.

• Out of many data structures of Pandas, two basic data structures-Series and DataFrame.

 Series:
• 1-dimensional

• Homogeneous-all the elements must be of same data type in a series object.

• Value mutable- their element's value can change.

• Size immutable- size of a series object, once created, can't change.

• If you want to add/drop an element, internally a new series object will be created.

• It is an array of actual data.

• Series type object can be created in many ways using pandas library's Series().

• Syntax: ‹Series object> =pd.Series(data,index)

• Common series attributes are:

Index, value, dtype, shape, nbytes, ndim, size, itemsize, hasnans, empty etc.

• A slice object is created from Series using a syntax of <object>[start:end:step].

• It applies on vector operations.

• Arithmetic operations on two Series type objects, the data is aligned on the
basis of matchingindexes.

 DataFrame:
• 2-dimensional

• Heterogeneous- a DataFrame object can have elements of different data types.

• Value mutable- their element's value can change.

• Size-mutable- size of a Dataframe object, once created, can change in place.

• So, you can add/drop elements in an existing dataframe object.

• It is actually a 2-dimensional (tabular and spreadsheet like) labelled array.

• It is an ordered collection of columns where columns may store

different types of dataeg., numeric or sting or floating point or Boolean

type etc.

• It has two indexes or we can say that two axes - a row index (axis=0) and a column index (axis
=1).
• It is like a spreadsheet where each value is identifiable with the combination
of row index and column index.

• There is no condition of having all data of same type across columns.

• You can easily change its values.

• < dataframe>=panda. DataFrame(<a 2D datastructure>,\


[columns=<columnsequence>],[index=<index sequence»l)

• While creating a dataframe with a nested or 2d Dict., Python interprets the outer
Dict. keys as thecolumns and the inner keys as the row indices.

• Common dataframe objects include: index, columns, axes, dtypes, sixe, shape,
values, empty, ndim,T.

• Transpose of a dataframe is available through< DF>.T

• When you assign something to a column of dataframe, then for existing column, it
will change thedata values and for non-existing column, it will add a new column.

• A column can be deleted using del command

• Pandas library makes available two functions for pivoting - the pivot() and
pivot_table()functions.

• With pivot(), if there are multiple entries for a column's value for the same values
for index(row), itleads to error.

• The pivot_table() pivots the data by aggregating it, thus it can work with duplicate entries.

• Commonly used aggregate functions are countt(), sumt(), meant(), mediant(),


mint(), maxt(), stdt(),vart(), madt().

• Func. Isnull() checking if a DataFrame has missing values.

• Func. fillnat() fills the missing values.

• To join two dfs, one can use functions - concatt(), joint()and merget().

 Graph (matplotlib):
• Data visualization basically refers to the grafical or visual representation of
information and datausing visual elements like charts, graphs, and maps etc.

• The matplotlib is a Python library that provides many interfaces and functionally
for 2D-graphicssimilar to MATLAB's in various forms.

• PyPlot is a collection of methods within matplotlib which allow user to construct 2D

plots easily andinteractively PyPlot essentially reproduces plotting fuctions and

behaviour of MATLAB.
• In order to use pyplot on your computers for data visualization, you need to first
imprt it in yourPython envt.

Byissuing import command for matplotlib.pyplot.

• Some commomly used chart types are line chart, bar chart, pie chart, scatter chart ete.

• You can create line charts by using pyplot's plot() function.

• You can change line color, width, line-style, marker-type, marker-color,


marker-size in plot()function.

• The scatter chart is a graph of plotted points on two axes that show the relationship
between two setsof data.

• You can create scatter charts using either plot function or scatter() function.

• A bar graph/Chart is a graphical display of data using bar() of different heights.

• You can create bar chart using pyplot's bar() function.

• Use bar() function to create horizontal bar chart.

• The pie() creates a pie chart.

• The plot area is known as figure and every other element of chart is contained in it.

• The axes can be labelled using xlabel() and ylabel() fune.

• Limits of axes can be defined using xlim() & ylim() func.

• Tick marks for axes defined by ticks() & yticks() functions.

• The title() function ads title to the plot.

• Using legend() function, one can add legends to a plot.

• The loc() provides the location for legend.

A histogram is a summarisation tool for

discrete data.Pyplot module's hist() lets you

create histograms.

• The boxplot() of pyplot lets you draw boxplots.

 Connectivity:
• The acronym CSV is short for Comma-Separated Values, which refers to a
tabular data saved asplaintext where data values are separated by commas.

• You can use pandas.read._csv() function to read

data from aCSV file in your dataframe.

• The < DF>.to_csv() function saves the data of dataframe in a CSV file.
• The function read_csv() is pandas' function and

to _csv() isdataframe sructure's function.

• The sqlites library can be used to interact with sqlite3 database from within python.

• You can use pandas.read._sql() func. to read data from an SQLtable in your dataframe.

• The < DF>.to_sql() function saves the data of

dataframe is anSQL table.

• An SQL database is a relational databse having data in tables called relations


and it uses a specialtype of query language,

Structured Query Language (SQL), to query upon manipulate data or to communicate with
database.

• In order to connect with MySQL from with a Python program, you must have the mysql
connector
package (mysql-connector-python) or pymysql installed.

• C:\<path>> pip install mysql-connector-python

• Import the mysql connector library along with importing pandas library.

Import pandas as pd

Import mysql.connector as sql

• To establish connection to a MySQL database using connect() func. of mysql.connector


package.

• If Python reports no error, it means you have successfully connected to MySQL


database. You can also check for successful connection using function is
connected() with connected object (which returns True, if connection is
successful,i.e., if you may write following additional code to check if theconnection is
successful or not).

• SQL Statement given inside the read_sql() function:

i) must end with a semicolon and

ii) ii) should be enclosed in quotes.

• String formatting uses this general form: f%v

where f is a template string and v species the value or values to be formatted. If


multiple values are tobe formatted, v must be a tuple. In a string we use a%s.
II. INTRODUCTION TO MYSQL:

DATABASE CONCEPT

Storing data in flat files or file-based system makes it difficult to analyze and retrieve
data from onebig file where it is stored. In these files, there is no structure
associated with data and common data may be repeated multiple times and also the
maintenance is poor.

Limitations of File-based approach are:

1. Difficulty in access

2. Data Redundancy

3. Data Inconsistency

4. Data Isolation

5. Data Dependence

6. Data Sharing Security and Control

issues Solution to all these problems is a

Database System.

DATABASE SYSTEMS

A database is an organized collection of structured information or data, typically


stored electronicallyin a computer system at a central location.

The database system did not maintain separate copies of same data. Rather, all the
data is kept at oneplace and all the applications that require data refer to the
centrally maintained database. In this system if any data is to be changed, it will be
made at just one place and the same changed information will be available to all the
applications referring to it.

DATABASE MANAGEMENT SYSTEM (DBMS)

A DBMS is a software system designed to maintain a database and provide data management

services.Advantages of Databases:

1. Database reduce the data redundancy to a large extent.

2. Database can control data inconsistency to a large extent.

3. Databases facilitates sharing of data.

4. Databases enforce standards.

5. Databases can ensure data security.


6. Databases ensure Data independence.

DBMS Key Concepts

1. Database Schema

• Sketch/skeleton/blueprint of a planned database

• Represents the design of tables, columns, relation, constraints and logical relationship

2. Database Instance

• Snapshot of a database that exists at a particular time

• Database instance can change over time

3. Metadata

• It refers to data about data

• The data in a table have certain properties and attributes that allow DBMS
to process datameaningfully

• Metadata is stored in Data Dictionary

4. Data Constraints

• It is the set of rules that define valid data

• Some primary constraints are: PRIMARY KEY, UNIQUE, CHECK, NOT NULL, FOREIGN KEY.

5. Query

• It is a type of command that retrieves data from a database stored on a server.

6. Data Manipulation

• It is the result of action queries

• It takes place when the data in tables is inserted, updated or deleted.

7.Database Engine

• It is the underlying software component that a DBMS uses to create, read,


update and delete datafrom a database.

• It has two major components: Storage

Engine andQuery Processor.


RELATIONAL DATA MODEL
In a relational data model, the data is organized into tables (i.e., rows and
columns). These tables are called relations. A row in a table represents the
relationship among a set of values. Since atable is a collection of such
relationships, it is generally referred to use mathematical term relation.

Terminologies used in relation model.

 Relation: A table using logically related data

 Domain: A pool of values from which actual values are drawn

 Tuple: A row of a relation

 Attribute: A column of a relation

 Degree: The number of columns in a relation

 Cardinality: The number of rows in a relation

 View: The virtual table that actually not exists but is derived from one or more
underlying basetables

 Primary Key: One or more attributes that can uniquely identify tuples within a relation

 Candidate key: Attribute that can serve as a primary key

 Alternate Key: A candidate key which is not a primary key

 Foreign Key: A non-key attribute whose values are derived from the primary
key of some othertable

MySQL - A Popular Relational Database Management


System

MySQL is free and open-source Relational Database Management System (RDBMS)


that usesStructured Query Language (SQL).It is downloaded from site
www.mysql.org

MySQL was developed by Michael Widenius also known as

Monty.MySQL has been named after Monty's Daughter My.

The logo of MySQL, the dolphin, is named as 'Sakila'.


MySQL Database System
MySQL database system refers to a combination of MySQL server instance and a
MySQL database.MySQL operates using client/server architecture in which the
server runs on the machine containing the databases and clients connect to server
over a network. MySQL is a multiuser database system, meaning several users can
access the database simultaneously.

Server listens for client requests coming through a network and accesses a database
content according to those requests and provide that to chents.

Clients are the programs that connect to the database server and issues
queries in a pre-specified format. MySQL is compatible with the standards-
based SQL.

Key features of MySQL

1. MySQL runs very last

2. Easy to use

3. Free and open-source software

4. Secure and portable

STRUCTURED QUERY LANGUAGE (SQL)


SQL is a language that enables you to create and operate on relational databases,
which are sets ofrelated information stored in tables. It was developed by IBM
researchers Raymond Boyce and Donald Chamberlin in 1970s.

Processing Capabilities of SQL

i. Provides commands for creating, defining and modifying relation schemas.

ii. Also includes commands to insert, delete and modify tuples.

iii. Can be used with other programming languages like Python,C++, JAVA, etc.

iv. Authorization is required to manipulate SQL database.

v. Integrity

vi. Transaction and session controlling options available.

Classification of SQL Statements

SQL provides many different types of commands used for different purposes. SQL
commands can bedivided into following categories:

a. Data Definition Language (DDL.)

b. Data Manipulation Language

(DML)c.Transaction Control

Language (TCL)
d. Data Control Language (DCL) DDL Statements:

Data Definition Language (DDL) allows us to perform tasks related to data definition.
Using DDL wecan perform tasks like:

• CREATE, ALTER, DROP schema objects

• GRANT and REVOKE privileges

• ANALYSE, CHECK, REPAIR, RESTORE -TABLE etc.

DML Statements:

Data Manipulation Language (DML) allows us to perform tasks related to data


manipulation. UsingDML we can perform tasks like:

• Retrieval of information (SELECT)

• Insertion of new information (INSERT INTO)

• Deletion of information (DELETE)

• Modification of data (UPDATE)

TCL Statements:

A transaction is one complete unit of work, it is successfully completed if and only


if all its constituent steps are successfully completed. Transaction Control
Language (TCL) allows us tomanage and control transactions. Using TCL, we can
perform tasks like:

• Make all the changes by the statement permanent (COMMIT)

• Undo all the changes since the beginning of transaction or since a save point (ROLLBACK)

• Mark a point up to which all earlier statements have been successfully completed
and if required onecan undo changes up to this very point (SAVEPOINT)

• Set property for current transaction (SET TRANSACTION)

DCL Statements:

Data Control Language (DCL) allows us to control the access to data stored in a
database. Using DCLwe can perform tasks like:

• Allow specific user to perform specific tasks (GRANT)

• Allows to remove granted permissions of a user

(REVOKE)Basic Elements of MySQL's SQL

1. Literals: It refers to a fixed data value. It can be of any datatype.

2. Data Types:

• Numeric types: INT, FLOAT, DOUBLE, DECIMAL


• String types: CHAR, VARCHAR, BLOB or TEXT • Date and Time types:
DATE, TIME,DATETIME, etc.

3. Nulls:

When a column in a row has no value, it is said to contain a null. Nulls can appear in
columns of anydatatype if they are not restricted by NOT NULL or PRIMARY KEY
constraints.

4. Comments:

A comment is a text that is not executed and it is only for documentation purpose. It
can appearbetween anykeywords, parameters or punctuation marks in a statement.

A comment can be included by the following means:

♦ Begin the comment with /* and end it with */

♦ Begin comment with --(followed by a space)

♦ Begin the comment with #

COMMANDS OF SQL
Creating and using Database:

To create a database the CREATE DATABASE command is used, as

follows.Syntax: CREATE DATABASE «Database Name»;

Ex: CREATE DATABASE School;

The above statement creates a database with the name School. To work with this
database thisdatabase should be opened using USE statement, as follows

Syntax: USE

«Database_Name»;Ex:

USE School;

Viewing Tables of a Database:

To see the tables, present in a database, the statement SHOW TABLES; can be used.

Creating a Table:

A table in the database can be created using CREATE TABLE

command, as followsSyntax: CREATE TABLE <TableName>

(<ColumnName1> <DataType1>,

«ColumnName2><DataType2>, ,

«ColumnNameN> <DataTypeN>);

Ex: CREATE TABLE STUDENT (RollNo INTEGER, Name


VARCHAR(15), Class CHAR(3), DOB DATE);

Inserting Data into a Table:

INSERT INTO command can be used to insert rows of data into a table. Its usage is

as follows.Syntax: INSERT INTO <TableName> (<ColumnName1>,

‹ColumName2>, ...,

<ColumnNameN») VALUES

(«Value1>, <Value2>, ‹Value3>,...

«ValueN>);

Ex: INSERT INTO STUDENT (RollNo, Name, Class, DOB)

VALUES(154, 'Rajesh', 11c, 1996-05-06);

Retrieving Data of a Table:

The SELECT command is used to display data of a table. It is also possible to display
the filtered datafrom the table.

To Display all the rows and columns

of TableSyntax: SELECT * FROM

<TableName>; Ex: SELECT * FROM

Student;

To Display selected Columns and all Rows:

Syntax: SELECT <ColumnName1>, <ColumnName2>, ....

FROM <TableName>,

Ex: SELECT Name, DOB FROM Student;

To Display selected Columns and selected Rows:

Syntax : SELECT <ColumnName1>,

<ColumnName2>, ..FROM <TableName> WHERE

Condition:

Ex: SELECT Name, DOB FROM Student WHERE Class = '11C;

Eliminating Redundant Data with DISTINCT Keyword:

Syntax : SELECT DISTINCT <ColumnName1>,


<ColumnName2»,...FROM <TableName>;

Ex: SELECT DISTINCT Class FROM Student;


SORTING THE RESULTS (USING ORDER BY):

The result obtained using SELECT statement is displayed in the order in which the
rows were enteredin the table using the

INSERT INTO statement. The results of the SELECT statement can be displayed in
the ascending ordescending values of a single column or multiple columns using
ORDER BY clause.

Syntax: SELECT <column name›, [<column name>. | WHERE

«Condition list>| ORDER BY ‹column name›;

Ex: SELECT * FROM Student ORDER BY

Marks1;Ex: SELECT * FROM Student ORDER

BY Name;

To display data in descending order, DESC keyword is used in

ORDER BY clause. However, it is not necessary to specify ASC for ascending


order as it is thedefault order.

Ex: SELECT * FROM Student ORDER BY Marks1 DESC;

SORTING ON COLUMN ALIAS:

If a Column alias is defined on a column, we can use it for displaying rows in an


ascending ordescending order using ORDER BY clause:

Ex: SELECT Name, Marks1 AS

TotalFROM Student

ORDER BY Total;

UPDATE STATEMENT:

The UPDATE statement is used to update the data of the

table.WHERE clause is also applicable to this statement.

Syntax: UPDATE < table_name› SET <column name» =

<value>,[ <column name> = <value>, -]

[WHERE <condn»);

Ex: UPDATE Student SET Marks1 = 94;


The above statement sets the Column Marks1 value of all rows to 94 of the table
Student. To applythis to specific rows, WHERE clause can be applied along with
UPDATE statement

Ex: UPDATE Student SET Marks1 = 94 WHERE name = 'Monica Rana';

DELETE STATEMENT:

DELETE statement is used to delete rows from a table. DELETE removes the entire
row, not theindividual column values.

Syntax: DELETE FROM < tablename> [ Where <

condn>];Ex: DELETE FROM Student WHERE

Rollno = 14;

DELETE statement can be used to delete all rows of the table also.

The following statement can be used to delete all the rows from Student table.

Ex: DELETE from


Student;
Functions in MySQL
A function is a special type of predefined command set that performs some
operations and returns asingle value.

These functions are of two types:

1. Single row function: works on individual rows of a table.

2. Aggregate functions: works on multiple rows and gives one output.

Single rows functions String functions:

I. CHAR(): Returns character for integer passed.

II. CONCAT(): Concatenates two strings.

III. LCASE(): Converts string into lowercase.

IV. SUBSTR(): Extracts substring from a string.

V. LEFT(): Returns specified leftmost characters.

VI. LTRIM(): Removes spaces from left of given string.

VII. RTRIM(): Removes spaces from right of given string.

VIII. TRIM(): Removes trailing and leading spaces.

IX. INSTR(): Searches for a string in given string

X. LENGTH(): Returns length of string in byte.

XI. LEFT(): Returns specified leftmost characters.


XII. RIGHT(): Returns specified rightmost characters.

XIII. MIDO: Returns specified string as per position.

Numeric Functions:

I. MOD(): Returns remainder.

II. POWER(): Returns m".

III. ROUND(): Round offs as per need.

IV. SIGN(): Returns Sign of number.

V. SQRT(): Returns square root of given number.

VI. TRUNCATE(): Returns numbers with digits deleted.

Date/Time Function:

I.CURDATE(): Returns current

date. II.DATE(): Returns date

part of format.

III. MONTH(): Returns month part of format.

IV. MONTHNAME(): Returns month name for date.

V. DAY(): Returns day part of date.

VI. YEAR(): Returns year part of date.

VII. DAYNAME(): Returns name of weekday.

VIII. DAYOFMONTH(): Returns day of month.

IX. DAYOFWEEK(): Returns day of week.

X. DAYOFYEAR(): Returns day of year.

XI. NOW(): Returns current date and time.

XII. SYSDATE(): Returns time of function execution.

Aggregate Functions:

There are four aggregate functions:

I. AVG(): Computes average of given data.

II. COUNT(): Counts number of rows.

III. MAX(): Returns maximum value of a column.

IV. MIN(): Returns minimum value of a column.


III.Practical
Synopsis On
Library Stock Management System

Introduction of Project Library Stock Management System is a software system wherethe management of entire library
is computerized. The library management system is designed using Python as front end and MySQL as the secured
backend database. In this project the details are maintained like book details, student details, Booking details and fine
details. The book issue and return process of book for the student, returning the book, stock of book, etc all are
computerized and the management is done without any difficulty.

The reports can be viewed completely and the head of the management daily or weekly or monthly can review it. For
school auditing it will be more useful.
This Proposed System will be interactive, faster and user-friendly for the end users. Using the library management
system, the following activities can be performed. Issue, return of book, adding or deleting student, stock verification.

Mission of the Project


The mission is to facilitate easy management and administration of a library with capabilities to do issue or returning of
the books, entering new student or deleting existing students, fine calculation, stock of book, etc. Using the automated
library management software. One can keep detailed records or info on an unlimited amount of students. The system lets
the user know which books are available for issue at any point of time. This makes the issue / return of books
considerably faster. And thus helps the library in better management and reduce a lot of paper work as well as
manpower.

Modules :-

● Add Book
● Add Member
● Modify Book Information
● Modify Student Information
● Issue book / Return book
● Report menu
● Special menu
● Close application
Software Requirement Specification
:-Python
MySQL

Hardware Specification:-Processor :
Pentium IV +Clock Speed : 2 GHz
RAM : 512 MB
Hard disk Capacity : 80 GBKeyboard :
101 Keys Mouse : Optical Mouse
Software Specification:- Front End :
Python

Back End : MySQL


Operating System : Windows XP or above
Program

import mysql.connector from datetime


import date
from prettytable import PrettyTablefine_per_day =1.0
#global variable def clear():
for _ in range(65):
print()
def add_book():
conn = mysql.connector.connect(
host='127.0.0.1', database='library', user='root', password='abcd') cursor = conn.cursor()
title = input('Enter Book Title :') author = input('Enter
Book Author : ')
publisher = input('Enter Book Publisher : ')pages = input('Enter
Book Pages : ')
price = input('Enter Book Price : ') edition = input('Enter
Book Edition : ')copies = int(input('Enter copies : '))
sql = 'insert into book(title,author,price,pages,publisher,edition,status) values ( "' + \title + '","'
+
author+'",'+price+','+pages+',"'+publisher+'","'+edition+'","available");' for _ in range(0,copies):
cursor.execute(sql)conn.close()
print('\n\nNew Book added successfully')
wait = input('\n\n\n Press any key to continue ............................. ')
def add_member():
conn = mysql.connector.connect(
host='127.0.0.1', database='library', user='root', password='abcd') cursor = conn.cursor()
name = input('Enter Member Name :')
clas = input('Enter Member Class & Section : ')address =
input('Enter Member Address : ') phone = input('Enter Member
Phone : ')

email = input('Enter Member Email : ')


sql = 'insert into member(name,class,address,phone,email) values ( "' + \name + '","' +
clas+'","'+address+'","'+phone + \
'","'+email+'");'
#sql2 = 'insert into transaction(dot,qty,type) values
("'+str(today)+'",'+qty+',"purchase");'
#print(sql)

cursor.execute(sql)conn.close()
print('\n\nNew Member added successfully')
wait = input('\n\n\n Press any key to continue ............................. ')
def modify_book():
conn = mysql.connector.connect(
host='127.0.0.1', database='library', user='root', password='abcd') cursor = conn.cursor()
clear()
print('Modify BOOK Details Screen ')print('-'*120)
print('\n1. Book Title') print('\n2. Book
Author') print('\n3. Book Publisher')
print('\n4. Book Pages') print('\n5. Book
Price') print('\n6. Book Edition')
print('\n\n')
choice = int(input('Enter your choice :')) field = ''
if choice == 1:field = 'title'
if choice == 2: field = 'author'
if choice == 3:
field = 'publisher'if choice ==
4:
field = 'pages'if choice
== 5:
field = 'price'
book_id = input('Enter Book ID :')
value = input('Enter new value :') if field =='pages'
or field == 'price':
sql = 'update book set ' + field + ' = '+value+' where id = '+book_id+';'else:
sql = 'update book set ' + field + ' = "'+value+'" where id = '+book_id+';' #print(sql)
cursor.execute(sql)
print('\n\n\nBook details Updated ......................... ')
conn.close()
wait = input('\n\n\n Press any key to continue ............................. ')
def modify_member():
conn = mysql.connector.connect(
host='127.0.0.1', database='library', user='root', password='abcd') cursor = conn.cursor()
clear()
print('Modify Memeber Information Screen ')print('-'*120)
print('\n1. Name') print('\n2.
Class') print('\n3. address')
print('\n4. Phone') print('\n5.
Emaile') print('\n\n')
choice = int(input('Enter your choice :')) field =''
if choice == 1: field ='name'
if choice == 2: field = 'class'
if choice ==3: field ='address'
if choice == 4: field = 'phone'
if choice == 5: field = 'email'
mem_id =input('Enter member ID :')value =
input('Enter new value :')
sql = 'update member set '+ field +' = "'+value+'" where id = '+mem_id+';'#print(sql)

P
a
g
e

cursor.execute(sql) 9
print('Member details Updated ...................... ')
conn.close()
wait = input('\n\n\n Press any key to continue ............................. ')
def mem_issue_status(mem_id): conn =
mysql.connector.connect(
host='127.0.0.1', database='library', user='root', password='abcd') cursor = conn.cursor()
sql ='select * from transaction where m_id ='+mem_id +' and dor is NULL;'#print(sql)
cursor.execute(sql) results =
cursor.fetchall()return results
def book_status(book_id):
conn = mysql.connector.connect(
host='127.0.0.1', database='library', user='root', password='abcd') cursor = conn.cursor()
sql = 'select * from book where id ='+book_id + ';'cursor.execute(sql)
result = cursor.fetchone()return result[5]
def book_issue_status(book_id,mem_id):conn =
mysql.connector.connect(
host='127.0.0.1', database='library', user='root', password='abcd')cursor = conn.cursor()
sql = 'select * from transaction where b_id ='+book_id + ' and m_id ='+ mem_id +'and dor is NULL;'
cursor.execute(sql) result =
cursor.fetchone()return result
def issue_book():
conn = mysql.connector.connect(
host='127.0.0.1', database='library', user='root', password='abcd') cursor = conn.cursor()
clear()
print('\n BOOK ISSUE SCREEN ')
print('-'*120)
book_id = input('Enter Book ID : ') mem_id = input('Enter
Member ID :')

result = book_status(book_id)
result1 = mem_issue_status(mem_id)#print(result1)
today = date.today()if len(result1)
== 0:
if result == 'available':
sql = 'insert into transaction(b_id, m_id, doi)
values('+book_id+','+mem_id+',"'+str(today)+'");'
sql_book = 'update book set status="issue" where id ='+book_id + ';'cursor.execute(sql)
cursor.execute(sql_book)
print('\n\n\n Book issued successfully')else:
print('\n\nBook is not available for ISSUE... Current status :',result1) else:
if len(result1)<1:
sql = 'insert into transaction(b_id, m_id, doi) values(' + \
book_id+','+mem_id+',"'+str(today)+'");'
sql_book = 'update book set status="issue" where id ='+book_id + ';'#print(len(result))
cursor.execute(sql)
cursor.execute(sql_book)
print('\n\n\n Book issued successfully')else:
print('\n\nMember already have book from the Library')#print(result)
conn.close()
wait = input('\n\n\n Press any key to continue ............................. ')
def return_book():
a
conn = mysql.connector.connect( g
host='127.0.0.1', database='library', user='root', password='abcd') cursor = conn.cursor() e
global fine_per_dayclear()
print('\n BOOK RETURN SCREEN ') 1
print('-'*120) 1
book_id = input('Enter Book ID : ') mem_id = o
input('Enter Member ID :')today =date.today() f

2
4
result = book_issue_status(book_id,mem_id) if result==None:
print('Book was not issued...Check Book Id and Member ID again..') else:
sql='update book set status ="available" where id ='+book_id +';' din = (today -
result[3]).days
fine = din * fine_per_day # fine per data
sql1 = 'update transaction set dor ="'+str(today)+'" , fine='+str(fine)+' whereb_id='+book_id +' and
m_id='+mem_id+' and dor is NULL;'
cursor.execute(sql)
cursor.execute(sql1)
print('\n\nBook returned successfully')conn.close()
wait = input('\n\n\n Press any key to continue ............................. ')
def search_book(field):
conn = mysql.connector.connect(
host='localhost', database='library', user='root', password='abcd')cursor = conn.cursor()
clear()
print('\n BOOK SEARCH SCREEN ')
print('-'*120)
msg ='Enter '+ field +' Value :'title =
input(msg)
sql ='select * from book where '+ field + ' like "%'+ title+'%"'cursor.execute(sql)
records = cursor.fetchall()clear()
print('Search Result for :',field,' :' ,title)print('-'*120)
for record in records:
print(record)
conn.close()
wait = input('\n\n\n Press any key to continue ............................. ')
def search_menu():while True:
clear()
print(' S E A R C H M E N U ')
print("\n1. Book Title") print('\n2. Book Author')
print('\n3. Publisher') print('\n4. Exit to main
Menu')print('\n\n')
choice = int(input('Enter your choice ...: '))field =''
if choice == 1:
field='title' if choice ==
2:
field = 'author'if choice ==
3:
field = 'publisher'if choice ==
4:
break search_book(field)
def reprot_book_list():
conn = mysql.connector.connect(
host='127.0.0.1', database='library', user='root', password='abcd') cursor = conn.cursor()
clear()
print('\n REPORT - BOOK TITLES ')
print('-'*120)
sql ='select * from book'
cursor.execute(sql) records =
cursor.fetchall()for record in records:
print(record)
conn.close()
wait = input('\n\n\nPress any key to continue .............................. ')
def report_issued_books():
conn = mysql.connector.connect(
host='127.0.0.1', database='library', user='root', password='abcd') cursor = conn.cursor()
clear()
print('\n REPORT - BOOK TITLES - Issued')print('-'*120)
sql = 'select * from book where status = "issue";'cursor.execute(sql)
records = cursor.fetchall()for record in
records:

P
print(record)
a
conn.close() g
wait = input('\n\n\nPress any key to continue .............................. ') e
def report_available_books():
conn = mysql.connector.connect( 1
host='127.0.0.1', database='library', user='root', password='abcd') cursor = conn.cursor() 3
clear()
o
print('\n REPORT - BOOK TITLES - Available')print('-'*120) f
sql = 'select * from book where status = "available";'cursor.execute(sql)
records = cursor.fetchall()for record in 2
records: 4
print(record)
conn.close()
wait = input('\n\n\nPress any key to continue .............................. ')
def report_weed_out_books(): conn =
mysql.connector.connect(
host='127.0.0.1', database='library', user='root', password='abcd') cursor = conn.cursor()
clear()
print('\n REPORT - BOOK TITLES - Weed Out')print('-'*120)
sql = 'select * from book where status = "weed-out";'cursor.execute(sql)
records = cursor.fetchall()for record in
records:
print(record)
conn.close()
wait = input('\n\n\nPress any key to continue .............................. ')
def report_stolen_books():
conn = mysql.connector.connect(
host='127.0.0.1', database='library', user='root', password='abcd') cursor = conn.cursor()
clear()
print('\n REPORT - BOOK TITLES - Stolen')print('-'*120)
sql = 'select * from book where status = "stolen";'

cursor.execute(sql) records =
cursor.fetchall()for record in records:
print(record)
conn.close()
wait = input('\n\n\nPress any key to continue .............................. ')
def report_lost_books():
conn = mysql.connector.connect(
host='127.0.0.1', database='library', user='root', password='abcd') cursor = conn.cursor()
clear()
print('\n REPORT - BOOK TITLES - lost')print('-'*120)
sql = 'select * from book where status = "lost";' cursor.execute(sql)
records = cursor.fetchall()for record in
records:
print(record)
conn.close()
wait = input('\n\n\nPress any key to continue .............................. ')
def report_member_list():
conn = mysql.connector.connect(
host='127.0.0.1', database='library', user='root', password='abcd') cursor = conn.cursor()

clear()
print('\n REPORT - Members List ')print('-'*120)
sql = 'select * from member'
cursor.execute(sql)
records = cursor.fetchall()for record in
records:
print(record)
conn.close()
wait = input('\n\n\nPress any key to continue .............................. ')

def report_fine_collection():
conn = mysql.connector.connect(
host='127.0.0.1', database='library', user='root', password='abcd')
\ cursor = conn.cursor()
sql ='select sum(fine) from transaction where dor ="'+str(date.today())+'";'cursor.execute(sql)
result = cursor.fetchone() #always return values in the form of tupleclear()
print('Fine collection')print('-'*120)
print('Total fine collected Today :',result[0])print('\n\n\n')
conn.close()
wait = input('\n\n\nPress any key to continue .............................. ')
def report_menu():while True:
clear()
print(' R E P O R T M E N U ')
print("\n1. Book List") print('\n2. Member List')
print('\n3. Issued Books') print('\n4. Available
Books') print('\n5. Weed out Book') print('\n6.
Stolen Book') print('\n7. Lost Book') print('\n8.
Fine Collection') print('\n9. Exit to main Menu')
print('\n\n')
choice = int(input('Enter your choice ........................ '))
if choice == 1:
reprot_book_list() if choice ==
2:
report_member_list() if choice == 3:
report_issued_books() if choice == 4:
report_available_books() if choice == 5:
report_weed_out_books() if choice == 6:
report_stolen_books()
if choice == 7:

report_lost_books()if choice ==
8:
report_fine_collection()if choice == 9:
break
def change_book_status(status,book_id):conn =
mysql.connector.connect(
host='127.0.0.1', database='library', user='root', password='abcd') cursor = conn.cursor()
sql = 'update book set status = "'+status +'" where id ='+book_id + ' and status
="available"' cursor.execute(sql)
print('Book status changed to ',status)print('\n\n\n')
conn.close()
wait = input('\n\n\nPress any key to continue .............................. ')

def special_menu():while True:


clear()
print(' S P E C I A L M E N U')
print("\n1. Book Stolen") print('\n2. Book
Lost') print('\n3. Book Weed out')print('\n4.
Return Book') print('\n\n')
choice = int(input('Enter your choice ........................ '))
status=''
if choice == 1:
status ='stolen'if choice ==
2:
status = 'lost'if choice
== 3:
status = 'weed-out'if choice ==
4:
break
book_id = input('Enter book id :')
change_book_status(status,book_id)

CREATE DATABASE IF NOT EXISTS `library` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `library`;
-- MySQL dump 10.13 Distrib 5.5.16, for Win32 (x86)
-- Host: localhost Database: library
-- Server version 5.5.27

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;


/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS,
FOREIGN_KEY_CHECKS=0
*/;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE,
SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

-- Table structure for table `member`

DROP TABLE IF EXISTS `member`;


/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `member` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` char(30) DEFAULT NULL,
`class` char(15) DEFAULT NULL,
`address` char(100) DEFAULT NULL,
`phone` char(15) DEFAULT NULL,
`email` char(60) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

-- Dumping data for table `member`


--LOCK TABLES `member` WRITE;

/*!40000 ALTER TABLE `member` DISABLE KEYS */;


INSERT INTO `member` VALUES (6,'Aditya verma','12
science','tilda','0000000000','[email protected]'),(7,'Anjali','12
Mathe','aps','0000000000','[email protected]'),(8,'Kamesh B.','12
Mathe','ambikapur','1234567890','[email protected]');
/*!40000 ALTER TABLE `member` ENABLE KEYS
*/; UNLOCK TABLES;

-- Table structure for table `book`

DROP TABLE IF EXISTS `book`;


/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `book` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`title` char(60) DEFAULT NULL,

`author` char(50) DEFAULT NULL,


`pages` int(4) DEFAULT NULL,
`price` float(6,2) DEFAULT NULL,
`status` char(10) DEFAULT NULL,
`publisher` char(60) DEFAULT NULL,
`edition` char(15) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=30 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

-- Dumping data for table `book`

LOCK TABLES `book` WRITE;


/*!40000 ALTER TABLE `book` DISABLE KEYS */;
INSERT INTO `book` VALUES (20,'Jorden IP','neetu
gaikwad',244,250.00,'stolen','airhant','2021'),(21,'airhant all in one','neetu
gaikwad',244,250.00,'stolen','airhant','2021'),(22,'all on one physics','AP
Dillon',400,450.00,'lost','airhant','2021'),(23,'all on one physics','AP Dillon',400,450.00,'weed-
out','airhant','2021'),(24,'NCERT IP','ncert',230,230.00,'available','ncert','2021'),(25,'NCERT
IP','ncert',230,230.00,'available','ncert','2021'),(26,'NCERT
IP','ncert',230,230.00,'available','ncert','2021'),(27,'NCERT
IP','ncert',230,230.00,'available','ncert','2021'),(28,'Mathematics','R.S.
Agrwall',780,1299.00,'available','RS publisher','2022'),(29,'Mathematics','R.S.
Agrwall',780,1299.00,'available','RS publisher','2022');
/*!40000 ALTER TABLE `book` ENABLE KEYS
*/; UNLOCK TABLES;
--
-- Table structure for table `transaction`

DROP TABLE IF EXISTS `transaction`;


/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `transaction` (
`tid` int(11) NOT NULL AUTO_INCREMENT,
`b_id` int(11) DEFAULT NULL,
`m_id` int(11) DEFAULT NULL,
`doi` date DEFAULT NULL,
`dor` date DEFAULT NULL,
`fine` float(5,2) DEFAULT NULL,
PRIMARY KEY (`tid`)
) ENGINE=MyISAM AUTO_INCREMENT=20 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `transaction`

LOCK TABLES `transaction` WRITE;


/*!40000 ALTER TABLE `transaction` DISABLE KEYS */;
INSERT INTO `transaction` VALUES (17,20,6,'2022-03-02','2022-03-02',0.00),(18,21,6,'2022-03-
07','2022-03-07',0.00),(19,24,7,'2022-03-08','2022-03-08',0.00);
/*!40000 ALTER TABLE `transaction` ENABLE KEYS
*/; UNLOCK TABLES;

-- Dumping events for database 'library'

/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;


/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2022-03-08 10:48:25


OUTPUT
P
a
g

You might also like