Learn Coding 2 Books in 1 A Practical Guide To Learn Python and SQL
Learn Coding 2 Books in 1 A Practical Guide To Learn Python and SQL
2 Books in 1:
A Practical Guide to Learn Python
and SQL. Discover the Secrets of
Programming and Avoid Common
Mistakes. Exercises Included
Jason Crash
Easy Navigator
During World War II, the war stimulated the need for computing in society.
Weapon design requires calculations, such as the design of a tank or the
outer hull of a submarine trajectory. The militarization of society requires
calculations, such as train scheduling, resource allocation, and population
mobilization. As for the missiles and high-tech projects like nuclear bombs,
they need massive amounts of computing. Computing itself could even
become a weapon. It’s worth noting that it was Alan Turing who came up
with the idea of a universal computer theoretical concept for the future
development of the computer to make a theoretical preparation. The top
prize in computer science is now named after Turing in honor of his great
service. The Z3 computer, invented by the German engineer Konrad Zuse,
can write programs. This invention made the world all set for the evolution
of the modern computer.
The most commonly thought of computers are desktops and laptops. In fact,
the computer also exists in smartphones, cars, home appliances, and other
devices. However, no matter how variable the shape, these computers all
follow the von Neumann structure. But in the details, there are big
differences between computers. Some computers use a multi-level cache,
some have only a keyboard without a mouse, and some have tape storage.
The hardware of a computer is a very complicated subject. Fortunately,
most computer users don’t have to deal directly with the hardware. This is
due to the operating system (OS).
An operating system is a set of software that runs on a computer and
manages its hardware and software resources. Both Microsoft’s Windows
and Apple’s IOS are operating systems. When we program, most of the
time it’s through the operating system, which is the middleman to deal with
the hardware. The operating system provides a set of system calls, which is
what the operating system supports. When a system call is called, the
computer performs the corresponding operation—alike with pressing a key
on a piano, and the piano produces a corresponding rhythm. The operating
system, therefore, defines a number of library functions to group system
calls to compose a particular function, like a chord made up of several tones
—and by programming, we take all these functions and libraries to create
beautiful music that is useful.
There are plenty of books on this subject on the market—thanks again for
choosing this one! Every effort was made to ensure it is full of as much
useful information as possible. Please enjoy!
Chapter 1: Python
This chapter gives a brief introduction to why programming is needed,
along with a short introduction about Python.
As you can see, when you click enter on the keyboard, the screen then
displays:
Oh, my name is Jesus Christ
The input print is the name of a function. The print() function has a specific
function, and the print() function simply prints characters on the screen. The
function is followed by a parenthesis that says the character you want to
print is, “Oh, my name is Jesus Christ.” The double quotation marks in
parentheses are not printed on the screen. The double quotation marks mark
out ordinary characters from program text such as print to avoid confusion
on the computer. You can also replace double quotes with a pair of single
quotes.
The second way to use Python is to write a Program File that the Python
Program file is written in. Py is the suffix, which can be created and written
with any text editor. The appendix describes the common text editor for
different operating systems. Create a file introduction.py, write the
following, and save it:
print("Oh, my name is Jesus Christ")
As you can see, the program content here is exactly the same as it was on
the command line. Compared with the command line, program files are
suitable for writing and saving a large number of programs.
Run the introduction.py, and you’ll see that Python also prints, “Hello
World! On the screen!” The contents of the program file are the same as
those typed on the command line and produce the same results. Program
files are easier to save and change than programs that are entered directly
from the command line, so they are often used to write large numbers of
programs.
Another benefit of program files is the ability to add comments. Comments
are words that explain a program and make it easier for other programmers
to understand it. Therefore, the content of the comment is not executed as a
program. In a Python program file, where every line starting with # is a
comment, we can annotate the hello.py.
print("Oh, my name is Jesus Christ") #Display those words on the screen
If you have too many comments to fit in a single line, you can use a
multiline comment.
""" Author: sample Function: Use this to display words """ print('Oh, my name is Jesus Christ')
The terminal will display information about Python, such as its version
number, followed by a command-line prompt for Python. If you want to
exit Python, type:
>>>exit()
If you want to run a Python Program in your current directory, append the
name to Python or Python 3:
$python installation.py
If the file is not in the current directory, you need to specify the full path of
the file, such as:
$python /home/authorname/installation.py
We can also change the installation.py to an executable script. Just add the
Python interpreter you want to use to the first line of the installation.py:
#!/usr/bin/env python
In the terminal, change the installation.py to executable:
$chmod installation.py
Then, on the command line, type the name of the program file, and you’re
ready to run it using the specified interpreter:
$./installation.py
2 ) Linux
Linux systems are similar to MAC systems, and most come preloaded with
Python. There are many Linux systems that offer something like
Homebrew’s software manager, which, for example, is installed under
Ubuntu using the following command:
$sudo apt-get install python
Under Linux, Python is used and run in much the same way as on the MAC,
and I won’t go into that again.
3) Windows Operating System
For the Windows operating system, you need to download the installation
package from the official Python Web site. If you don’t have access to
Python’s web site, search engines for keywords like “Python Windows
download” to find other download sources. The installation process is
similar to installing other Windows software. In the install screen,
Customize the installation by selecting Customize, in addition to selecting
Python components, check:
Add python.exe to Path
Once installed, you can open the Windows command line and use Python as
you would on a Mac.
Virtualenv
You can install multiple versions of Python on a single computer, and using
virtualenv creates a virtual environment for each version of Python. Here’s
how to install virtualenv using Python’s included pip.
$pip install virtualenv
You can create a virtual space for a version of Python on your computer,
such as:
$virtualenv –p /usr/bin/python3.5 virtualpythonexample
In the above program, we pass the value (for example, 276) to the variable
exvariable, a process called Assignment. The assignment is represented by
an equal sign in Python. With the assignment, a variable is created. From a
hardware perspective, the process of assigning a value to a variable is the
process of storing the data in memory. A variable is like a small room in
which data can be stored. Its name is the house number. The assignment is
to send a guest to the room.
"Send Harry to Room exvariable"
Output is:
Sachin
In computer programming, many variables are often set, with each variable
storing data for a different function. For example, a computer game might
record the number of different resources that a player has, and it would be
possible to record different resources with different variables.
Diamond = 50 # means 50 points
Bronze = 20 # means 20 points
Fire = 10 # means 10 points
During the game, you can add or subtract resources, depending on the
situation. For example, if a player chooses to cut bronze, he adds twenty
more points. At this point, you can add 5 to the corresponding variable.
bronze = bronze + 20
print(bronze)
#prints 40
Output is:
40
The computer first performs the operation to the right of the assignment
symbol. The original value of the variable is added to 20 and assigned to the
same variable. Throughout the game, the variable bronze plays a role in
tracking data. The player’s resource data is stored properly.
Variable names are directly involved in computation, which is the first step
towards abstract thinking. In mathematics, the substitution of symbols for
numbers is called Algebra. Many middle school students today will set out
Algebraic equations to solve such mathematical problems as “chicken and
rabbit in the same cage.” But in ancient times, Algebra was quite advanced
mathematics. The Europeans learned advanced Algebra from the Arabs,
using the symbolic system of Algebra to free themselves from the shackles
of specific numbers and to focus more on the relationship between logic
and symbols. The development of modern mathematics on the basis of
Algebra laid a foundation for the explosion of modern science and
technology. Variables also give programming a higher level of abstraction.
The symbolic representation provided by variables is the first step in
implementing code reuse. For example, the code used to calculate the
amount of cash needed to buy a house:
50000*(0.3 + 0.1)
When we look at more than one suite at a time, the price of 50000 changes.
For convenience, we can write the program as:
Sellingprice= 50000
needed= total *(0.3+ 0.1)
print(needed)
#prints the output
Output is:
20000
This way, you only need to change the value of 50000 each time you use
the program. Of course, we’ll see more ways to reuse code in the future.
But variables, which use abstract symbols instead of concrete numbers, are
representative.
Chapter 5: Data Types in Python
This chapter deals with datatypes that variables use. At the start, variables
had no data types. However, for the convenience of programmers, data
types have been implemented in different programming languages. Python
supports a lot of basic data types along with few advanced data types like
tuple and dictionary. We will have a detailed description of data types.
As you can see, the value later assigned to the variable replaces the original
value of the variable. Python having the freedom to change the
characteristics of a variable type is called Dynamic Typing. Not all
languages support dynamic typing. In a Static Typing language, variables
have pre-specified types. A specific type of data must be stored in a specific
type of variable. Dynamic typing is more flexible and convenient than static
typing.
Even if you can change it freely, Python’s variables themselves have types.
We can use the function type() to see the type of the variable. For example:
datatype_integer = 64.34
print(type(datatype_integer))
Since sequences are also used to store data, we cannot help but read the data
in the sequence. The elements in a sequence are ordered, so you can find
the corresponding elements based on their position in each element. The
positional index of a sequence element is called the subscript (Index). The
subscript for a sequence in Python starts at 0, which is the corresponding
subscript for the first element. There are historical reasons for this, in
keeping with the Classic C language. We try to reference elements in the
sequence:
The data in the table can be changed so that individual elements can be
assigned values. You can use the subscript to indicate which element you
want to target.
Dictionaries
In Python, there are also special data types called dictionaries. We will now
explain these data types in detail.
Dictionaries are similar to tables in many ways. It is also a container that
can hold multiple elements. But dictionaries are not indexed by location.
The dictionary allows you to index data in a custom way.
>>>thisisdictionary = {"harry":22, "Ron":37,"Hermoine":64}
>>>type(thisisdictionary) # To input the dictionary values
Output is:
37
Mathematical Operators
1) Addition
>>>4 + 2
2) Subtraction
>>>4 - 2
3) Multiplication
>>>4 * 2
4) Division
>>>4 / 2
5) Remainder
>>>4 % 2
In addition to the usual numeric operations, strings can also be added. The
effect is to concatenate two strings into one character.
String
Input:
>>>" I am a follower of " + "Christianity"
Output:
I am a follower of Christianity
Input:
>>>"Example" *2
Output:
ExampleExample
Comparison Operator
Python uses comparison operators like ==, >, and < in its program. Below,
we will explain with an example.
Program code is below:
first = 34
second = 44
if ( first > second)
print "First one is larger"
else
print "Second one is larger"
Output is:
Second one is larger
Logical Operators
In addition to numerical operations, computers can also perform logical
operations. It’s easy to understand the logic if you’ve played a killing game
or enjoyed a detective story. Like Sherlock Holmes, we use logic to
determine whether a statement is true or false. A hypothetical statement is
called a proposition, such as “player a is a killer.” The task of logic is to
find out whether a proposition is true or false.
Computers use the binary system, where they record data in zeros and ones.
There are technical reasons why computers use binary. Many of the
components that make up a computer can only represent two states, such as
the on and off of a circuit, or the high and low voltages. The resulting
system is also relatively stable. If you use the decimal system, some
computer components will have 10 states, such as the voltage into 10 files.
That way, the system becomes complex and error-prone. In Binary Systems,
1 and 0 can be used to represent the true and false states. In Python, we use
the keywords True and False to indicate True and False. Data such as True
and False are called Boolean values.
Sometimes, we need further logical operations to determine whether a
complex proposition is true or false. For example, in the first round, I
learned that “player a is not a killer” is true, and in the second round, I
learned that “player B is not a killer” is true. So in the third round, if
someone says, “player a is not a killer, and player B is not a killer,” then
that person is telling the truth. If the two propositions connected by “and”
are respectively true, then the whole proposition is true. Virtually, we have a
“and” of the logical operation.
In the and operation, when both subpropositions must be true, the
compound proposition connected by and is true. The and operation is like
two bridges in a row. You must have both bridges open to cross the river, as
shown in figure 2-1. Take, for example, the proposition that China is in Asia
and Britain is in Asia. The proposition that Britain is in Asia is false, so the
whole proposition is false. In Python, we use and for the logical operation
of and.
>>>True and True # True
>>>False and True # false
>>>False and False # True
We can also compound the two propositions with “or.” Or is humbler than
an aggressive “and.” In the phrase “China is in Asia, or Britain is in Asia,”
for example, the speaker leaves himself room. Since the first half of this
sentence is true, the whole proposition is true. “Or” corresponds to the “or”
logic operation.
In the “or” operation, as long as there is a proposition for true, then “or”
connected to the compound proposition is true. The or operation is like two
bridges crossing the river in parallel. If either bridge is clear, pedestrians
can cross the river.
The above logic operation seems to be just some life experience and does
not need a computer such as complex tools. With the addition of a judgment
expression, a logical operation can really show its power.
Operator Precedence
If there is more than one operator in an expression, consider the precedence
of the operation. Different operators have different precedence. Operators
can be grouped in order of precedence. Below is the list of operator
precedence in an order.
Exponent powers have the highest precedence, followed by the
mathematical operator multiplication, division, addition, and subtraction.
And the next comes Bitwise operators followed by logical operators at the
end.
Chapter 7: Execution and Repetitive Tasks
This chapter deals with if-else statement and different types of loop
structures that help in repetitive tasks in programming.
If Structure
So far, the Python programs we’ve seen have been instruction-based. In a
program, computer instructions are executed sequentially. Instructions
cannot be skipped, nor repeated backward. The first programs were all like
this. For example, to make a light come on ten times, repeat ten lines of
instructions to make the light come on.
In order to make the program flexible, early programming languages added
the function of “jump.” With jump instructions, we can jump to any line in
the program during execution and continue down. For example, to repeat
execution, jump to a line that has already been executed. Programmers
frequently jump forward and backward in their programs, for convenience.
As a result, the program runs in a sequence that looks like a tangle of
noodles, hard to read and prone to error.
Programmers have come to realize that the main function of a jump is to
execute a program selectively or repeatedly. Computer experts have also
argued that with the grammatical results of “selection” and “loop,” “jump”
is no longer necessary. Both structures change the flow of program
execution and the order in which instructions are executed. Programming
languages have entered a structured age. Compared with the “Spaghetti
Program” brought about by the “jump,” the structured program becomes
pleasing to the eye. In modern programming languages, the “jump” syntax
has been completely abolished.
Let’s start with a simple example of a choice structure: if a house sells for
more than $200,000, the transaction rate 3% or 4%. We write a program
using a selection structure.
Below is the program code:
price = 340000
if
expectedprice> 200000:
fixedtax= 0.04
Else:
fixedtax= 0.03
print(fixedtax)
#prints 0.03
Output is:
0.04
In this process, there’s an if that we haven’t seen before. In fact, the
function of this sentence is easy to understand. If the total price exceeds
200,000, then the expected tax is 4%: otherwise, the transaction rate is 3%.
The keywords, if and else, each have a line of code attached to them, with a
four-space indentation at the beginning of the dependent code. The program
will eventually choose whether to execute the if dependent code or the else
dependent code, depending on whether the condition after the if holds. In
short, the if structure branches off from the program.
If and else can be followed by more than one line:
price = 340000
if
total > 200000:
Print ("rate is above 200,000")
fixedtax= 0.04
else:
Print ("rate is below 200,000")
fixedtax= 0.03
print(fixedtax)
# The result is 0.04
Output is:
rate is above 200,000
As you can see, code that is also an if or else has four spaces indented.
Keywords if and else are like two bosses, standing at the head of the line.
There’s a little brother standing back from the boss. The boss only by the
terms of winning, standing behind his younger brother, has a chance to
appear. The last line of the print statement also stands at the beginning of
the line, indicating that it is on an equal footing with if and else. The
program doesn’t need conditional judgment; it always executes this
sentence.
Else is not necessary; we can only write if program. For example:
price= 340000
if
price > 200000:
Print ("total price over $200,000")
Stand Back
Python features indentation to indicate the dependencies of your code. As
we show, the design for indenting code relationships is derived from the
ABC language. For comparison, let’s look at how C is written:
if ( price > 0 ) {
selling= 1;
buying= 2;
}
The program means that if the variable price is greater than 0, we will do
the two assignments included in the parentheses. In C, a curly brace is used
to represent a block of code that is subordinate to the if. The average
programmer also adds indentation to the C language to distinguish the
dependencies of instructions. But indenting is not mandatory. The following
does not indent the code, in the C language can also be normal execution,
and above the results of the program run no difference:
In Python, the same program must be written in the following form:
if price> 0:
selling= 1
buying= 2
In Python, the parentheses around 0 are removed, the semicolon at the end
of each statement is removed, and the curly brackets around the block are
also removed. There’s more—the colon (:) and the indentation of four
spaces in front of 1 and 2. By indenting, Python recognizes that both
statements are subordinate to the if. Indenting in Python is mandatory in
order to distinguish between dependencies. The following procedure will
have an entirely different effect:
if price> 0:
selling= 1
buying= 2
Here, only selling that is 1 is subordinate to if, and the second assignment is
no longer subordinate to if. In any case, buying will be assigned to 2.
It should be said that most mainstream languages today, such as C, C++,
Java, JavaScript, mark blocks with curly braces, and indentation is not
mandatory. This syntax is derived from the popularity of the C language.
On the other hand, while indenting is not mandatory, experienced
programmers write programs in these languages with indenting in order to
make them easier to read. Many editors also have the ability to indent
programs automatically. Python’s forced indentation may seem
counterintuitive, but it’s really just a matter of enforcing this convention at
the syntactic level so that programs look better and are easier to read. This
way of writing, with four spaces indented to indicate affiliation, is also seen
in other Python syntax constructs.
There are three blocks, led by if, Elif, and else. Python first detects the
condition of the if, skips the block that belongs to the if the condition is
false, and executes the else block if the condition of the Elif is still false.
The program executes only one of three branches, depending on the
condition. Since the result has a value of 1, only the if part is executed in
the end. In the same way, you can add more elif between if and else to
branch your program.
We can also nest an if structure inside another if structure:
result = 5
if result> 1: # This condition holds, execute the Internal Code
print("result bigger than 1")
print("nice")
if result > 2: # nested if structure, the condition holds.
print("result bigger than 2")
print("Its good than before")
After making the first if judgment, if the condition holds, the program runs
in sequence and encounters the second if construct. The program will
continue to judge and decide whether to execute based on the conditions.
The second subsequent block is indented four more spaces relative to the if
to become the “little brother.” Programs that further indent are subordinate
to the inner if. In general, with the if construct, we branch the program.
Depending on the conditions, the program will take a different path.
For Loop
Loops are used to iterate through blocks of code. In Python, loops are either
for or while. Let’s start with the for loop. From the selection structure in
section 2.3, we have seen how to use indentation to represent the
membership of a block. Loops use similar notation. Programs that are part
of a loop and need to be repeated are indented, such as:
for input in [4,6.8,"love"]:
print(c) #prints each element in the list in turn
The loop is to take an element from the list [4,6,8, “love”] one at a time,
assign it to c, and execute the line belongs to the program for, which calls
the print() function to print out the element. As you can see, one of the basic
uses of for is to follow in with a sequence:
The 3-way range() function in the program indicates the number of times
you want to repeat. As a result, the program that belongs to for is executed
five times. Here, after the for loop, there is still the variable I, which counts
for each loop:
for result in range(7):
print(result, "This is crazy") # prints the sequence number and "This is crazy"
As you can see, the count provided by range() in Python also starts at 0, the
same as the index of the table. We also saw a new use of print(), which is to
specify multiple variables in parentheses, separated by commas. The
function print() prints them all.
Let’s look at a practical example of a for loop. We have previously used
Tuples to record the yearly interest rate on a mortgage.
thisisinteresttuple= (0.06, 0.07, 0.08, 0.1, 0.3)
While Loop
There is also a loop structure in Python, the while loop. The use of the
While is:
check= 0
while check< 20:
print(check)
check= check+ 1
# prints from 0 to 19
Skip or Abort
The loop structure also provides two useful statements that can be used
inside the loop structure to skip or terminate the loop. Continue skips this
execution of the loop for the next loop operation. Break stops the whole
loop.
for result in range(20):
if result == 2:
Continue
print(result)
# prints 0,1,3,4,5,6,7,8,9,11,13,15,17,19 notice that you skipped 2
When the loop executes until the result is 2, the if condition holds,
triggering continue, instead of printing result at this point—the program
proceeds to the next loop, assigns 3 to result, and continues to execute the
for subordinate statement. The continue simply skips a loop, while the
break is much more violent, and it terminates the entire loop.
for result in range(20):
if result == 2:
Break
Print (result) # prints only 0 and 1
When the loop reaches 2, the if condition holds, triggers the break, and the
entire loop stops. The program no longer executes the statements inside the
for loop.
Defining Functions
Let’s first make a function. The process of making a function is also called
defining a function. We call this function squareofnum(). As the name
suggests, the function calculates the sum of the squares of two numbers:
def squareofnum(first,second):
first = first**2
second = second**2
result = first+ second
return result
The first keyword to appear was “def”. This keyword tells Python, “here
comes the definition of the function.” The keyword def is followed by
squareofnum, the name of the function. After the function name, there are
parentheses to indicate which arguments the function takes—namely, first
and second—in parentheses. Parameters can be multiple in number or none
at all. According to Python Syntax, the parentheses following a function
should be preserved even if no input data is available.
In defining the function, we use symbols(variables) first and second to refer
to the input data. Until we actually use the function, we won’t be able to
specify what numbers first and second are. So, defining a function is like
practicing martial arts. When you actually call a function, you use the actual
input data to determine how hard you want to hit it. Arguments function
like variables inside a function definition, participating in any line of
instruction in a symbolic form. Because the parameter in a function
definition is a formal representation, not real data, it is also called a
parameter.
In defining the function squareofnum(), we complete the symbolic square
summation with parameters first and second. In the execution of a function,
the data represented by the parameter does indeed exist as a variable, as we
will elaborate on later.
At the end of the parentheses, you come to the end of the first line. There’s
a colon at the end, and the last four lines are indented. We can infer that the
colon and indenting represent the subordination of the code. So, the four
indented lines of code that follow are the kids of the function
squareofnum(). A function is an encapsulation of code. When a function is
called, Python executes the statements that belong to the function until the
end of the statement. For squareofnum(), the first three lines are the familiar
arithmetic statements. The last sentence is returned. The keyword return is
used to describe the return value of a function, which is the function’s
output data.
As the last sentence of a function, the function ends on return, regardless of
whether there are other function definition statements after it. If you replace
squareofnum() with the following:
def squareofnum(first,second):
first = first **2
second = second**2
result = first+ second
return result
Print (“ Here ends the result”)
Then, when the function executes, it will only execute to return result. The
latter statement, print(), although also a function, is not executed. So return
also has the ability to abort the function and specify the return value. In
Python Syntax, return is not required. If there is no return, or if there is no
return value after return, the function returns None. None is the empty data
in Python, used to indicate nothing. The Return Keyword also returns
multiple values. Multiple values are followed by return, separated by
Commas.
The function min() takes multiple arguments and returns the largest of
them. If we can’t remember the function min() and its parameters, we can
ask help().
>>> help(min)
As you can see, the function Min() is called in two ways. Our previous call
was in the second way. In addition, the documentation explains the basic
functions of the function Min().
The function Min() belongs to Python’s own defined built-in function, so
the documentation is ready in advance. For our custom functions, we need
to do it ourselves. The process is not complicated, so here’s a simple
notation for the function cube():
def sumdefined(first,second):
"""return the square sum of two arguments"""
first= first**2
second= second**2
third = first+ second
return third
Parameter Passing
Basic Pass Parameters
Passing data as arguments to a function is called parameter passing. If there
is only one parameter, then parameter passing is simple, simply mapping
the only data entered at the time of the function call to this parameter. If you
have more than one parameter, Python determines which parameter the data
corresponds to when you call the function based on its location. For
example:
def argument(first, second, third):
"""print arguments according to their sequence"""
print(first, second, third)
print_arguments(1, 3, 5)
print_arguments(5, 3, 1)
print_arguments(3, 5, 1)
In each of the three calls to the program, Python determines the relationship
between the arguments by their locations. If you find that positional
arguments are rigid, you can pass them in the form of keywords. When we
define a function, we give the parameter a symbolic token, which is the
parameter name. Keyword passing is based on the parameter name to make
the data and symbols on the corresponding. Therefore, if the keyword is
passed in at the time of the call, the correspondence of the location is not
followed. Use The function definition above and pass it as a parameter
instead:
print_arguments(third=5,second=3,first=1)
As you can see from the results, Python no longer uses locations to
correspond to parameters but instead uses the names of parameters to
correspond to parameters and data. Positional and keyword passing can be
used together, with one part of the argument being passed based on location
and the other on the name of the argument. When a function is called, all
positional arguments appear before the keyword arguments. Therefore, you
can call:
print_arguments(1, third=5,second=3)
But if you put the position parameter 1 after the keyword parameter C5,
Python will report an error:
print_arguments(third=5, 1, second=3)
The first time you call the function, you enter three data, which corresponds
to three parameters, so the parameter C corresponds to 1. On the second call
to the function, we provided only 3 and 2 data. The function maps 3 and 2
to the shape parameters A and B, depending on the position. By the time we
get to parameter C, there is no more data, so C will take its default value of
10.
Pass the Parcel
All of the above methods of passing arguments require that the number of
arguments is specified when defining the function. But sometimes when we
define a function, we don’t know the number of arguments. There are many
reasons for this, and sometimes it’s true that you don’t know the number of
parameters until the program is running. Sometimes, you want the function
to be more loosely defined so that it can be used for different types of calls.
At this point, it can be very useful to pass parameters by packing them.
As before, the package pass-through takes the form of a location and a
keyword. Here’s an example of a package position pass:
def place(*all_arguments):
print(type(all_arguments))
print(all_arguments)
postion (2,7,9)
position(5,6,7,1,2,3)
Both calls are based on the same package() definition, although the number
of parameters is different. Calling package(), all data is collected into a
tuple in sequence. Inside the function, we can read incoming data through
tuples. That’s the package. Pass it on. In order to remind you that the
Python parameter all is a package. When we define package(), we prefix the
tuple name all with an asterisk.
Let’s take another look at the package keyword pass example. This
parameter passing method collects the incoming data into a dictionary:
def package(**arguments):
print(type(arguments))
print(arguments)
package(first=1,second=9)
package(fourth=2,fifth=1,third=11)
You can go a step further and mix the package pass with the basic pass.
They appear in the order is Location → Keyword → package location →
package keyword. With parcel passing, we have more flexibility in
representing data when defining functions.
Unwrap
In addition to being used for function definition, * and * * Can also be used
for function calls. In this case, both are to implement a syntax called
unpacking. UNWRAPPING allows us to pass a data container to the
function and automatically decompose it into arguments. It should be noted
that the package transferring and UNWRAPPING is not the opposite
operation, but two relatively independent functions. Here’s an example of
UNWRAPPING:
def packagediscontinue(first,second,third):
print(first,second,third)
args = (1233,42)
packagediscontinue(*args)
Then, when passing the dictionary args, each key-value pair of the
dictionary is passed as a keyword to the function packagediscontinue().
Unwrapping is used for function calls. When a function is called, several
arguments can also be passed in a mix. It’s still the same basic principle:
Location → Keyword → location Unwrapping → keyword unwrapping.
Recursion
GAUSS and Mathematical Induction
Recursion is the operation of a function call itself. Before we get to
recursion, let’s take a look at a short story by the mathematician GAUSS. It
is said that once the teacher punished the whole class by having to work out
the sum of 1 to 100 before going home. Only seven years old, Gauss came
up with a clever solution that became known as the gauss summation
formula. Here’s how we’ll solve GAUSS’s summation programmatically:
addition= 0
for result in range(1, 101):
addition= addition + i
print(addition)
As the program shows, a loop is a natural way to solve a problem. But this
is not the only solution, we can also solve the problem in the following
ways:
def sumgauss(result):
if result == 1:
return 1
Else:
return result+ sumgauss(result-1)
print(sumgauss(100))
The above solution uses Recursion, in which the function itself is called
within a function definition. In order to ensure that the computer does not
get stuck in a loop, recursion requires that the program have a Base Case
that can be reached. The key to recursion is to show the join condition
between the next two steps. For example, we already know the cumulative
sum of 1 to 64, which is Gaussian(64), then the summation of 1 to 64 can
easily be found: Gaussian(64) Gaussian(63) + 62.
When we use recursive programming, we start with the end result, which is
that in order to find Gaussian(100), the computer breaks the calculation
down to find Gaussian(99) and to find Gaussian(99) plus 100. And so on,
until you break it down into Gaussian(1), then you trigger the termination
condition, which is N1 in the if structure, to return a specific number 1.
Although the whole process of recursion is complicated, when we write a
program, we only need to focus on the initial conditions, the termination
conditions, and the join, not on the specific steps. The computer will be in
charge of the execution.
Recursion comes from mathematical induction. Mathematical Induction is a
Mathematical proof, often used to prove that a proposition is valid in the
range of natural numbers. With the development of modern mathematics,
proofs within the scope of natural numbers have actually formed the basis
of many other fields, such as mathematical analysis and number theory, so
mathematical induction is of vital importance to the whole mathematical
system.
The mathematical induction itself is very simple. If we want to prove a
proposition for the natural number N, then:
The first step is to prove that the proposition holds for n 1.
The second step is to prove that the proposition holds for N + 1 under the
assumption that N is an arbitrary natural number.
Function Stack
Recursion in the program requires the use of the Stack data structure. The
so-called data structure is the organization of data stored by a computer.
The stack is a kind of data structure, which can store data in an orderly way.
The most prominent feature of the stack is “Lifo, Last In, First Out”. When
we store a stack of books in a box, the books we store first are at the bottom
of the box, and the books we store later are at the top. We have to take the
books out of the back so that we can see and take out the books that were in
the first place. This is Lifo. The stack is similar to this book box, only “last
in, first out”. Each book, that is, each element of the stack, is called a frame.
The stack supports only two operations: Pop and push. The stack uses pop
operations to get the top element of the stack and push operations to store a
new element at the top of the stack.
As we said before, in order to Compute Gaussian(100), we need to pause
Gaussian(100) and start computing Gaussian(99). To calculate
Gaussian(99), pause Gaussian(99), and call Gaussian(98), and so on. There
will be many incomplete function calls before the termination condition is
triggered. Each time a function is called, we push a new frame into the
stack to hold information about the function call. The stack grows until we
figure out Gaussian(1), then we go back to Gaussian(2), Gaussian(3), and
so on. Because the stack is “backward advanced.”
“Out” feature, so each time just pop up the stack frame, it is what we need
Gaussian(2), Gaussian(3), and so on until the pop-up hidden in the bottom
frame Gaussian(100).
Therefore, the process of running a program can be seen as a stack first
growth and then destroy the stacking process. Each function call is
accompanied by a frame being pushed onto the stack. If there is a function
call inside the function, another frame is added to the stack. When the
function returns, the corresponding frame is pushed off the stack. At the end
of the program, the stack is cleared, and the program is complete.
Scope of Variables
With a function stack in place, the scope of a variable becomes simple. A
new variable can be created inside a function, such as the following:
def variable(first, second):
third= first+ second
return third
print(variable(4, 6))
In fact, Python looks for variables in more than the current frame. It also
looks for variables that are defined outside the function in Python’s main
program. So, inside a function, we can “see” variables that already exist
outside the function. For example, here’s the program:
def variable():
print(result)
result= 5
inner_var()
When a variable is already in the main program, the function call can create
another variable with the same name by assigning it. The function takes
precedence over the variable in its own function frame. In the following
program, both the main program and the function external() have an info
variable. Inside the function external(), the info inside the function is used
first:
def externalvariable():
detail = "Authors Python"
print(detal)
detail= "This is crazy"
externalvariable()
print(detail)
And the function uses its own internal copy, so the internal action to Info
does not affect the external variable info. The arguments to a function are
similar to the arguments inside the function. We can think of a parameter as
a variable inside a function. When a function call is made, the data is
assigned to these variables. When the function returns, the variables
associated with these parameters are cleared. But there are exceptions, such
as the following:
When we pass a table to a function, table B outside the function changes.
When the argument is a data container, there is only one data container
inside and outside of the function, so the operation inside the function on
the data container affects the outside of the function. This involves a subtle
mechanism in Python that we’ll explore in more detail. Now, it is important
to remember that for the data container, changes inside the function affect
the outside.
Introducing Modules
There used to be a popular technical discussion on the Internet: “How do
you kill a dragon with a programming language?” There were many
interesting answers, such as the Java Language “Get out there, find the
Dragon, develop a multi-tier dragon kill framework, and write a few articles
about it... but the dragon wasn’t killed.” The answer was a mockery of
Java’s complex framework. “C.”
The language is: “Get there, ignore the Dragon, raise your sword, cut off the
Dragon’s head, find the princess... hang the princess.” The answer is to
praise the power of the C language and the commitment of the C
community to the Linux kernel. As for Python, it’s simple:
Import functionlibrary;
People who know Python modules smile at this line of code. In Python, A.
The. Py file constitutes a module. With modules, you can call functions in
other files. The import module was introduced to reuse existing Python
programs in new programs. Python, through modules, allows you to call
functions in other files. Let’s start with a first.py document that reads as
follows:
def smile():
print("HaHaHaHa")
And write a laugh.py file in the same directory. Introduce the first module
into the program:
from first import smile
for result in range(10):
smile()
With the import statement, we can use the smile() function defined in the
laugh.py in the URL. In addition to functions, we can also introduce data
contained in other files. Let’s say we’re in a module (trail.Py). Write:
text = "Hello programmer"
If you are a custom module, put it where you see fit and change the Python
path environment. When Python path contains the path of a module, Python
finds that module.
When Python introduces a module, it goes to the search path to find the
module. If the introduction fails, it is possible that the search path was set
incorrectly. We can set the search path as follows.
Inside Python, you can query the search path in the following way:
>>>import best
>>>print(best.path)
As you can see, best.path is a list. Each element in the list is a path that will
be searched. You can control the search path for Python by adding or
removing elements from this list.
The above change method is dynamic, so each time you write the program,
you add related changes. We can also set the PYTHONPATH environment
variable to change the Python search path statically. On Linux, you can use
them. Add the following line to the bashrc file to change the
PYTHONPATH:
export PYTHONPATH=/home/user/mylib:$PYTHONPATH
Additional tools for installing third-party modules are available under EPD
Python and Anaconda and can be found at the official website. You can use
the following command to find all installed modules, as well as the version
of the module:
$pip freeze
Chapter 9: Reading and Writing Files in Python
Once you understand the basics of object-oriented programming, you can
take advantage of the wide variety of objects in Python. These objects can
provide a wealth of functionality, as we will see in this chapter for file
reading and writing, as well as time and date management. Once we get
used to these powerful objects, we can implement a lot of useful features.
The fun of programming is to implement these functions in a program and
actually run them on a computer.
Storage
Documents
We know that all the data in Python is stored in memory. When a computer
loses power, it’s like having amnesia, and the data in the memory goes
away. On the other hand, if a Python program finishes running, the memory
allocated to that program is also emptied. For long-term persistence, Python
must store data on disk. That way, even if the power goes out or the
program ends, the data will still be there.
The disk does store data in file units. For a computer, the essence of data is
an ordered sequence of binary numbers. If you take a sequence of bytes,
that is, every eight bits of a binary number, then that sequence of data is
called text. This is because an 8-bit sequence of binary numbers
corresponds to exactly one character in ASCII encoding. Python, on the
other hand, can read and write files with the aid of text objects.
In Python, you can create file objects with the built-in function open. When
you call open, you need to specify the file name and how to open the file:
f = open (filename,method)
A filename is the name of a file that exists on disk. Common ways to open a
file are:
"r" # to read an existing file
“w” # create a new file and write
“a” # if the file exists, write to the end of the file. If the file does not exist, a new file is created and
written
For example:
>>>f = open("harrypotter.txt","r")
This will instruct Python to read a text file named harrypotter. It’s a read-
only way to open a file called harrypotter.txt.
With the object returned above, we can read the file:
file= f.read(30)
# Read 30 bytes of data
file= f.readline()
# read a line
file= f.readlines()
# read all the rows and store them in a list, one row for each element.
If you want to write a line, you need to add a newline at the end of the
string. On UNIX systems, the line feed is “\n”. In Windows, the line feed is
“\r \n”.
Example:
f.write(" This is the chamber of secrets \n") # UNIX
f.write("This is the chamber of secrets \r\n") # Windows
Opening the file port takes up computer resources, so close the file in a
timely manner with the close method of the file object after reading and
writing.
f.close()
Context Manager
File operations are often used with context managers. The context manager
is used in specifying the scope of use for an object. Once in or out of this
scope, special actions are called, such as allocating or freeing memory for
an object. The context manager can be used for file operations. For file
operations, we need to close the file at the end of the read and write.
Programmers often forget to close files, taking up resources unnecessarily.
The context manager can automatically close files when they are not
needed.
Here is an example of file manipulation.
f = open("Ron.txt", "w")
print(f.closed) # check to see if the file is open
f.write("I love Quidditch")
f.close()
print(f.closed) # print True
If we add the context manager syntax, we can rewrite the program to:
# use the context manager
with open("new.txt", "w") as f:
f.write("Hello World!")
print(f.closed)
The second part of the program uses with... as... Structure. The context
manager has a block that belongs to it, and when the execution of that block
ends, that is, when the statement is no longer indented, the context manager
automatically closes the file. In the program, we call F. Closed property to
verify that it is closed. With a context manager, we use indentation to
express the open range of a file object. For Complex programs, the presence
of indenting makes the coder more aware of the stages at which a file is
opened, reducing the possibility of forgetting to close the file.
The above context manager is based on the () special method of the f object.
When using the syntax of the context manager, Python calls the () method
of the file object before entering the block, and the file pair at the end of the
Block. The () method of image. In the () method of the file object, there is
self. Close () statement. Therefore, we do not have to close the file in clear
text when using the context manager.
Any object that defines a () method and a () method can be used by the
context manager. Next, we customize a class ram and define its () and ()
methods. Thus, objects from the Vow class can be used for the context
manager:
Program code is given below:
class ram(object):
def __init__(ayodhya, text):
ayodhya.text = text
def __enter__(ayodhya):
ayodhya.text = "You know " + Ayodhya.text
return ayodhya
def __exit__(ayodhya,exc_type,exc_value,traceback):
ayodhya.text = ayodhya.text + "!"
with ram("Its a kingdom") as myram:
print(myram.text)
print(myram.text)
When the object is initialized, the text property of the object is “Its a
kingdom”. As you can see, the object invokes the () and () methods as it
enters and leaves the context, causing the text property of the object to
change.
Pickle Pack
We can store the text in a file. But the most common objects in Python are
objects that disappear from memory when the program ends, or the
computer shuts down. Thus, can we save objects to disk?
You can do this with Python’s pickle package. Pickle means pickle in
English. Sailors at the Age of Discovery used to make pickles out of
vegetables and take them with them in cans. Pickle in Python has a similar
meaning. With the pickle package, we can save an object and store it as a
file on disk.
In fact, objects are stored in two steps. The first step is to grab the object’s
data out of memory and convert it into an ordered text, called Serialization.
The second step is to save the text to a file. When we need to, we read the
text from the file and then put it into memory, we can get the original
object. Here’s a concrete example, starting with the first step of
serialization, which converts an object in memory into a text stream:
import pickle
class Animal(object):
have_trunk = True
howtheyreproduce= "zygote"
winter= animal()
pickle_string = pickle.dumps(winter)
Using the pickle package’s dumps() method, you can convert an object to a
string. We then store the string in a file using the byte text storage method.
Step 2:
with open("winter.pkl", "wb") as f:
f.write(pickle_string)
The above procedure is deliberately divided into two steps to illustrate the
whole process better. Instead, we can take a dump() approach and do two
steps at a time:
import pickle
class Animal(object):
have_trunk = True
howtheyreproduce= "zygote"
winter= animal()
with open("winter.pkl", "w") as f:
pickle.dump(winter, f)
Object winter will be stored in the file winter (in the PKL). With this file,
we can read the object if necessary. The process of reading an object is the
opposite of that of storing it. First, we read the text from the file. Then,
using the pickle’s load() method, we convert the text as a string to an object.
We can also combine the above two steps using the pickled load() approach.
Sometimes, just reversing the recovery is not enough. An object depends on
its class, so when Python creates an object, it needs to find the appropriate
class. So when we read an object from the text, the class must already have
been defined in the program. For built-in classes that Python always has,
such as lists, dictionaries, strings, and so on, you don’t need to define them
in your program. For a userdefined class, however, you must first define the
class before you can load its objects from the file.
Here is an example of a read object:
import pickle
class animal(object):
have_trunk = True
howtheyreproduce= "zygote"
with open("winter.pkl", "rb") as f:
winter= pickle.load(f)
print(winter.have_trunk)
Chapter 10: Object-Oriented Programming Part
1
Having looked at Python’s process-oriented programming paradigm, we’ll
use a completely different programming paradigm in this chapter—object-
oriented. Python is not just a language that supports an object-oriented
paradigm. Under the multi-paradigm facade, Python uses objects to build its
large framework. As a result, we can get an early start in object-oriented
programming to understand Python’s deep magic.
To understand object orientation, you need to understand classes and
objects. Remember the process-oriented functions and modules that
improve the reusability of your program. Classes and objects also improve
program reusability. In addition, the class and object Syntax also enhances
the program’s ability to simulate the real world. “Emulation” is the very
heart of object-oriented programming.
The object-oriented paradigm can be traced back to the Simula language.
Kristen Nygaard is one of the co-authors of the language. He was recruited
by the Norwegian Ministry of Defence and then served at the Norwegian
Institute of Defence Sciences. As a trained mathematician, Kristen Nygaard
has been using computers to solve computational problems in defense, such
as nuclear reactor construction, fleet replenishment, and logistics supply,
etc. To solve these problems, Nygaard needed a computer to simulate the
real world. For example, such as what would happen if there was a nuclear
leak. Nygaard found that, following a procedural, instruction-based
approach to programming, it’s hard for him to program real-world
individuals. Take a boat, for example. We know it has some data, such as
height Degree, width, horsepower, draught, etc. It will also have some
movement, such as moving, accelerating, refueling, moored, and so on.
This ship is one Individuals. Some individuals can be grouped, such as
battleships and aircraft carriers are warships. Some individuals have
inclusive relationships, such as A ship has an anchor.
When people tell stories, they naturally describe individuals from the real
world. But for a computer that only knows the 0 / 1 sequence, it will just
mechanically execute instructions. Nygaard hopes that when he wants to do
computer simulations, it will be as easy as telling a story. He knew from his
military and civilian experience that such a programming language had
great potential. Eventually, he met Ole-Johan Dahl, a computer scientist.
VEGETA is helping Nygaard turned his idea into a novel language --
Simula. The name of the language is the very simulacrum that Nygaard
craves.
We can think of object orientation as a bridge between story and instruction.
The coder uses a story-based programming language.
The compiler then translates these programs into machine instructions. But
in the early days of computers, these extra translations consumed too many
computer resources. Therefore, the object-oriented programming paradigm
is not popular. Pure object-oriented languages are often criticized for their
inefficiencies.
With the improvement of computer performance, the problem of efficiency
is no longer a bottleneck. People turned their attention to the productivity of
programmers and began to explore the potential of object-oriented
languages. The first great success in the object-oriented world was the C++
language. Bjarne Stroustrup created the C++ language by adding object-
oriented syntax to the C language. C++ is a mixture of C language features,
so it looks very complex. Later versions of the Java language moved toward
a more purely object-oriented paradigm and quickly became commercially
successful. C++ and Java were once the most popular programming
languages. Microsoft’s later C# and Apple’s ongoing support for
OBJECTIVE-C were also typical object-oriented languages.
Python is also an object-oriented language. It’s older than Java. However,
Python allows programmers to use it in a purely procedural way, so its
object-oriented heart is sometimes overlooked. One of Python’s
philosophies is that “everything is an object.” Both the process-oriented
Paradigm we saw in Chapter 3, and the functional programming we will see
in the future, are, in fact, the result of special object simulations. Therefore,
learning object- orientation is a key part of learning Python. Only by
understanding Python’s objects can we see the full picture of the language.
Classes
When it comes to finding objects, the first thing we look at is a grammatical
structure called a class. The concept of class here is similar to the concept
of “class” in our daily life. In everyday life, we put similar things into a
group and give the Group A name. Animals, for example, have trunks in
common and reproduce by zygote. Any particular Animal is based on the
archetype of an Animal.
Here’s how we describe animals in Python:
class Animal(object):
trunk= True
howtheyreproduce= "zygote"
Here, we define a class with the keyword class. The class name is Animal.
In parentheses, there is a keyword object, which means something, that is,
an individual. In computer languages, we refer to individuals as objects. A
class does not. There can be more than one. Animals can include neighbor
elephant, the tiger running over the horizon, and a small yellow chicken
kept at home.
Colons and indenting describe the code that belongs to this class. In the
block of programs that fall under this category, we define two quantities—
one for the trunk, and the other for reproduction—called the attributes of
the class. The way we define animals is crude. Animals are just “hairy
things that reproduce.” Biologists would probably shake their heads if they
saw this, but we’re taking our first steps into a simulated world.
In addition to using data attributes to distinguish categories, we sometimes
also distinguish categories based on what these things can do. For example,
birds can move. In this way, the bird is distinguished from the type of
house. These actions have certain consequences—such as changes in
position due to movement. Some of these “behavior” properties are called
methods. In Python, you typically illustrate a method by defining a function
inside a class.
class Animal(object):
trunk= True
howtheyreproduce= "zygote"
def roar(self, sound):
print(sound)
Objects
We define classes, but as the function definition, this is still just a matter of
building weapons. To use this sharp tool, we need to go deep into the
object. By calling the class, we can create an object under the class. For
example, I have an animal named winter. It’s an object, and it belongs to an
animal. We use the previously defined animal to generate this object:
winter= Animal()
Use this sentence to create an object and explain that winter is an object that
belongs to Animals. Now, we can use the code already written in animal.
As an object, winter will have the properties and methods of an animal. A
reference to a property is made by a reference in the form of
object.attribute. For example:
print(winter.howtheyreproduce)
In the method set(), we set the object’s property color with the self
parameter. As with class attributes, we can pass objects. Property to
manipulate object properties. Since the object attribute depends on self, we
must operate on the class attribute within a method. Therefore, object
properties cannot be assigned an initial value directly below the class, like
class properties.
Python does, however, provide a way to initialize object properties. Python
defines a series of special methods. In a very specific way, it’s called the
Magic Method. A programmer can set special methods in a class definition.
Python deals with special methods in a particular way. For the class()
method, Python calls it automatically every time an object is created.
Therefore, we can initialize object properties inside the () method:
class Animal(object):
def __init__(self, sound):
self.sound = sound
print("my roar is", sound)
def roar(self):
print(self.sound)
winter= Animal("Gurrrrr")
winter.roar()
In the above class definition, we show how the class is initialized using the
roar() method. Whenever an object is created The def_init_() method is
called when, for example, the summer object is created. It sets the sound
property of the object. You can call this object property through self in the
roar() method. In addition to setting object properties, we can also set the
Add additional instructions in self(). These instructions are executed when
the object is created. When a class is called, it can be followed by a
Parameter list. The data put in here will be passed to the parameters of ().
With the () method, we can initialize object properties at object creation
time.
In addition to manipulating object properties, the self parameter also has the
ability to call other methods of the same class within a method, such as:
class Animal(object):
def roar(self, sound):
print(sound)
def roarcontinous(self, sound, n):
for i in range(n):
self.roar(sound)
winter= Animal()
winter.roarcontinous("gurrr", 10)
In the method roar(), we call another method in the class, roar(), through
self.
Successors
Subclasses
The category itself can be further subdivided into subcategories. Animals,
for example, can be further divided into Amphibians and Reptiles. In
object-oriented programming, we express these concepts through
Inheritance.
class Animal(object):
trunk= True
howtheyreproduce= "zygote"
def roar(self, sound):
print(sound)
class Amphibian(Animal):
waytheywalk= "bywalk"
edible = True
class Reptile(Animal):
In the class definition, the parenthesis is Animal. This shows that
Amphibian belongs to a subclass of Animal, namely Amphibian inherited
from animal. Naturally, Animals are the father of Amphibians. Amphibians
will have all of Animals attributes. Although we only declare winter as an
amphibian, it inherits the properties of the parent class, such as the data
attribute trunk, and the method attribute roar(). The New Reptile class also
inherited from Animal. When you create a Reptile object, the object
automatically has Animal properties.
Obviously, we can use inheritance to reduce the repetition of Information
and statements in the program. If we define Amphibians separately,
Amphibian and reptiles, rather than animals, have to be entered into the
amphibian and reptile definitions separately. The whole process can become
tedious, so inheritance improves the program’s reusability. In the most basic
case, the object is inside the parentheses of the class definition. The class
object is actually a built-in class in Python. It serves as the ancestor of all
classes.
Classification is often the first step in understanding the world. We learn
about the world by classifying all sorts of things. Ever since our human
ancestors, we’ve been sorting. The 18th century was a time of great
maritime discoveries when European navigators went around the world,
bringing back specimens of plants and animals that had never been seen
before. People are excited about the proliferation of new species, but they
also struggle with how to classify them. Carl Linnaeus has proposed a
classification system that paves the way for further scientific discoveries
through the subordination of parent and child classes. Object-oriented
language and its inheritance mechanism are just the conscious classification
process of simulating human beings.
Attribute Overlay
As mentioned above, in the process of inheritance, we can enhance the
functionality of a subclass by adding attributes in which the parent class
does not exist. In addition, we can replace properties that already exist in
the parent class, such as:
Amphibian is a subspecies of Animal. In Amphibian, we define the method
roar(). This method is also defined in Animal. As you can see, the
Amphibian calls its own defined roar() method instead of the parent class.
In effect, it’s as if the method roar() in the parent class is overridden by the
namesake property in the child class.
By covering methods, we can radically change the behavior of subclasses.
But sometimes the behavior of a subclass is an extension of the behavior of
a parent class. At this point, we can use the super keyword to call methods
that are overridden in the parent class, such as:
In the chicken roar() method, we use super. It is a built-in class that
produces an object that refers to the parent class. Using super, we call the
methods of the parent class in the method with the same name as the child
class. In this way, the methods of a subclass can both perform related
operations in the parent class and define additional operations of their own.
Operators
We know that list is the class of the list. If you look at the attributes of a list
with Dir(list), you see that one of the attributes is addition(). Stylistically,
addition() is a special method. What’s so special about it? This method
defines the meaning of the + operator for a list object. When two list objects
are added, the list is merged. The result is a consolidated list:
>>>print([10,32,43] + [45,26,49])
# This becomes [10,32,43,45,26,49]
There is an error message that the list object cannot be subtracted, that is,
the list does not define the “-” operator. We can create a subclass of the list
and add a subtraction definition by adding() methods, such as:
class Addsubstraction(list):
def substraction(self, b): a = self[:]
b = b[:]
while len(b) > 0:
element_b = b.pop()
if element_b in a: a.remove(element_b)
return a print(Addsubstraction([1,2,3]) - Addsubstraction([3,4]))
In the example above, the built-in function Len() returns the total number of
elements contained in the list. The built-in function subtraction() defines the
operation of “-” to remove elements from the first table that appear in the
second table. So, the two Addsubstraction objects that we created can be
subtracted. Even if the sub() method has already been defined in the parent
class, the method in the child class overrides the method with the same
name as the parent class when redefined in the child class. That is, the
operator will be redefined.
The process of defining operators is useful for complex objects. For
example, humans have multiple attributes, such as name, age, and height.
We can define human comparison by age alone. So that you can, for your
own purposes, take what wasn’t there the operation in is added to the
object. If you’ve been in military training, you’ve probably played a game
of “turn left, turn right.” When the drill master shouts commands, you must
take the opposite action. For example, if you hear “turn to the left,” you
must turn to the right. In this game, the operators “turn left” and “turn right”
are actually redefined.
Element References
Here are some common table element references:
li = [23, 42, 34, 49, 65, 86]
print(li[4])
When the above program runs to Li[4], Python finds and understands the []
symbol and calls the getitem() method.
li = [23, 42, 34, 49, 65, 86]
print(li.getitem(4))
Take a look at the following and think about what it corresponds to:
li = [23, 42, 34, 49, 65, 86]
li.setitem(4, 60) print(li)
The built-in function len() also makes writing easier than _len_().
Try the following and think of its corresponding built-in function. These are
called mathematical functions if said in the right way.
(-69).__abs__() # prints the absolute value of the element
(2.3).__int__() # prints the nearest integer value of the element
Here’s our output (Please don’t get confused because this is quite complex):
===> winter{'age': 4}
===> Amphibian {'walk': False, 'roar':, '__module__': '__main__', '__doc__': None, '__init__': }
===>Animal {'__module__': '__main__', 'roar':, '__dict__':, 'trunk': True, '__weakref__':, '__doc__':
None}
===>result {'__setattr__':, '__reduce_ex__'
The order is based on proximity to summer’s objects. The first part is about
the properties of the summer object itself, the age. The second part is about
the properties of the chicken class, such as the fly and _init_() methods. The
third part is the Bird class attribute, such as feather. The last part belongs to
the object class and has properties like this.
If we look at the properties of the object summer with the built-in Function
Dir, we see that the summer object contains all four parts. In other words,
the properties of objects are managed hierarchically. For all of the
properties that object summer has access to, there are four levels: summit,
Amphibian, Animal, and object. When we need to call a property, Python
will iterate down layer by layer until we find the property. Because objects
do not need to store the properties of their ancestor classes repeatedly, a
hierarchical management mechanism can save storage space.
An attribute may be defined repeatedly at different levels. As Python
traverses down, it picks the first one it encounters. This is how property
coverage works. In the output above, we see that both Chicken and Bird
have the roar() method. If you call the roar() method from winter, you will
be using a version of Amphibian that is closer to the object winter.
winter.roar()
Although rainy modifies the trunk attribute value, it does not affect
Animal’s class attribute. When we look at rainy’s object properties using
the following method, we see that a new object property named trunk is
created.
Print(rainy.__dict__)
Features
There may be dependencies between different properties of the same object.
When a property is modified, we want other properties that depend on that
property to change at the same time. At this point, we cannot store attributes
in a static dictionary manner. Python provides a variety of ways to generate
attributes on the fly. One of these is called a property. A property is a
special property. For example, we added an adult feature to the Amphibian
class. When the age of the object exceeds 1, adult is true; otherwise, false.
Here is the programming code:
class Animal(object):
trunk= True
class Amphibian(Animal):
walk = False
def __init__(self, age):
self.age = age
def adultage(self):
if self.age > 1.0:
return True
else:
return False
adultery = property(adultage) # property is built-in
winter= Amphibian(2)
print(winter.adultery) #True
winter.age = 0.5
print(winter.adult) #False
The property is created using the built-in function property(). Property() can
load up to four parameters. The first three arguments are functions that set
what Python should do when it gets, modifies, and deletes features. The last
parameter is a property of the document, which can be a string, for
illustration purposes.
The upper num is a number, and the Neg is a property that represents the
negative number. When a number is definite, its negative number is always
definite. When we modify a negative number, the value of the number itself
should also change. These two points are implemented by get() and set().
Del() indicates that if you delete the feature Neg, then the action that should
be performed is Delete attribute value. The last parameter of property()
(“I’m negative”) is the documentation for the feature neg.
_getatr_() method
In addition to the built-in function property, we can also use (self, name) to
query for properties that are generated on the fly. When we call a property
of an object, if the property cannot be found by mechanism, Python will call
the() method of the object to generate the property immediately, such as:
Each feature needs its own handler, and() can handle all the instant
generated properties in the same function. () can handle different properties
depending on the function name. For example, when we queried for the
attribute name male above, we threw an error of the AttributeError class.
Note that () can only be used to query for properties that are not in the
system.
(self, name, value) and (self, name) can be used to modify and delete
attributes. They have a wider range of applications and can be used for any
attribute.
Real-time attribute generation is a very interesting concept. In Python
Development, you might use this approach to manage the properties of
objects more reasonably. There are other ways to generate properties on the
fly, such as using the descriptor class. Interested readers may refer to this
code below.
class Animal(object):
trunk= True
class Amphibian(Animal):
walk = False
def __init__(self, age):
self.age = age
def __getattr__(self, name):
if recognition== "old":
if self.age > 1.0:
return True
else:
return False
else:
raise AttributeError(name)
winter = Amphibian(2)
print(winter.old) #True
winter.age = 0.5
print(winter.adult) #False
print(winter.male) # AttributeError
Dynamic Type
Dynamic Typing is another important core concept of Python. As I said
earlier, Python variables do not need to be declared. When assigning a
value, a variable can be reassigned to any other value. Python variables
change from wind to wind. The ability of sand is the embodiment of
dynamic type. Let’s start with the simplest assignment statement:
c= 3
In Python, the integer 3 is an object. The object’s name is “c”. But more
precisely, an object name is actually a reference to an object. An object is an
entity stored in memory. But we don’t have direct access to the subject. An
object name is a reference to that object. Manipulating Objects by reference
is like picking up beef from a hot pot with chopsticks. The object is beef,
and the object name is the good pair of chopsticks.
With the built-in function ID(), we can see which object the reference points
to. This function returns the object number.
c= 3
print(id(3))
print(id(c))
As you can see, after the assignment, object 3 and reference c return the
same number.
In Python, an assignment is simply to use the object name as a chopstick to
pick up other food. Each time we assign a value, we let the reference on the
left point to the object on the right. A reference can point to a new object at
any time:
c= 5
print(id(c))
c= "for"
print(id(c))
2. Garbage Collection
If you eat too much, you’ll get fat, and so will Python. As the number of
objects in Python increases, they take up more and more memory. But you
don’t have to worry too much about Python’s size, as it will be smart
enough to “lose weight” and start recycling in due course Garbage
Collection, which purges objects of no use. Garbage collection mechanisms
exist in many languages, such as Java and Ruby. While the ultimate goal is
to be slim, weight loss programs vary greatly from language to language.
In principle, when the reference count of an object in Python drops to zero,
meaning that there are no references to the object, the object becomes
garbage to be recycled. For example, if a new object is assigned to a
reference, the reference count of the object becomes 1. If the reference is
deleted and the object has a reference count of 0, then the object can be
garbage collected.
The code is below:
variable= [12, 24, 36]
del variable
What Is a Bug?
Bugs must be the most hated creatures a programmer can have. A bug in the
programmer’s eyes is a bug in a program. These bugs can cause errors or
unintended consequences. Many times, a bug can be fixed after the fact.
There are, of course, irremediable lessons. The European Ariane 5 rocket
exploded within a minute of its first launch. An after-action investigation
revealed that a floating-point number in the navigator was to be converted
to an integer, but the value was too large to overflow. In addition, a British
helicopter crashed in 1994, killing 29 people. The investigation revealed
that the helicopter’s software system was “full of flaws.” In the movie
2001: A Space Odyssey, the supercomputer HAL kills almost all of the
astronauts because of two goals in its program conflict.
In English, bug means defect. Engineers have long used the term bug to
refer to mechanical defects. And there’s a little story about using the word
bug in software development. A moth once flew into an early computer and
caused a computer error. Since then, bugs have been used to refer to bugs.
The moth was later posted in a journal and is still on display at the National
Museum of American History.
Code:
for result in range(5)
print(result)
# Python does not run this program. It will alert you to grammatical errors:
Output is:
SyntaxError: invalid syntax
There are no syntax errors in the following program, but when Python is
run, you will find that the subscript of the reference is outside the scope of
the list element.
result= [12, 24, 36]
print(result[4])
# The program aborts the error reporting
Output:
IndexError: list index out of range
The above type of Error that the compiler finds only at Runtime is called
the Runtime Error. Because Python is a dynamic language, many operations
must be performed at run time, such as determining the type of a variable.
As a result, Python is more prone to run-time errors than a static language.
There is also a type of Error called a Semantic Error. The compiler thinks
that your program is fine and can run normally. But when you examine the
program, it turns out that it’s not what you want to do. In general, such
errors are the most insidious and the most difficult to correct. For example,
here’s a program that prints the first element of a list.
mix = ["first", "second", "third"]
print(mix[1])
There is no error in the program, normal print. But what you find is that you
print out the second element, B, instead of the first element. This is because
the Python list starts with a subscript from 0, so to refer to the first element,
the subscript should be 0, not 1.
Debugging
The process of fixing a bug in a program is called debugging. Computer
programs are deterministic, so there is always a source of error. Of course,
sometimes spending a lot of time not being able to debug a program does
create a strong sense of frustration, or even a feeling that you are not
suitable for program development. Others slam the keyboard and think the
computer is playing with itself. From my personal observation, even the
best programmers will have bugs when they write programs. It’s just that
good programmers are more at peace with debugging and don’t doubt
themselves about bugs. They may even use the debug process as a kind of
training, to work with their computer knowledge by better understanding
the root cause of the error.
Actually, debugging is a bit like being a detective. Collect the evidence,
eliminate the suspects, and leave the real killer behind. There are many
ways to collect evidence, and many tools are available. For starters, you
don’t need to spend much time with these tools. By inserting a simple
print() function inside the program, you can see the state of the variable and
how far it has run. Sometimes, you can test your hypothesis by replacing
one instruction with another and seeing how the program results change.
When all other possibilities are ruled out, what remains is the true cause of
the error.
On the other hand, debug is also a natural part of writing programs. One
way to develop a program is Test-Driven Development (TDD). For Python
to be such a convenient, dynamic language, it’s a good place to start by
writing a small program that performs a specific function. Then, on the
basis of the small program, gradually modify, so that the program continues
to evolve, and finally, meet the complex requirements. Throughout the
process, you keep adding features, and you keep fixing mistakes. The
important thing is, you’ve been coding. The Python author himself loves
this kind of programming. So, debug is actually a necessary step for you to
write the perfect program.
When the transaction is over, the waiter puts the transaction behind him and
prepares to serve the next customer.
GET /start.html HTTP/3.0
Host: www.mywebsite.com
The early HTTP protocol had only the GET method. Following the HTTP
protocol, the server receives the GET request and passes the specific
resource to the client. This is similar to the process of ordering and getting a
Burger from a customer. In addition to the GET method, the most common
method is the POST method. It is used to submit data from the client to the
server, with the data to be submitted appended to the request. The server
does some processing of the data submitted by the POST method. The
sample request has a header message. The type of header information is
Host, which indicates the address of the server you want to access.
After receiving the request, the server will generate a response to the
request, such as:
HTTP/3.0 200 OK
Content-type: text/plain
Content-length: 10
Jesus Christ
Ok is a textual description of the status code 200, which is just for human
readability. The computer only cares about three-digit status codes. Status
Code, which is 200 here. 200 means everything is OK, and the resource
returns normally. The status code represents the class that the server
responded to. There are many other common status codes, such as:
302, Redirect: I don’t have the resources you’re looking for here,
but I know another place where xxx does. You can find it there.
404, Not Found: I can’t find the resources you’re looking for.
The next line, Content-type, indicates the type of resource that the body
contains. Depending on the type, the client can start different handlers (such
as displaying image files, playing sound files, and so on). Content-length
indicates the length of the body part, in bytes. The rest is the body of the
reply, which contains the main text data.
Through an HTTP transaction, the client gets the requested resource from
the server, which is the text here. The above is a brief overview of how the
HTTP protocol works, omitting many details. From there, we can see how
Python communicates with HTTP.
http.client Package
The client package can be used to make HTTP requests. As we saw in the
previous section, some of the most important information for HTTP
requests are the host address, request method, and resource path. Just clarify
this information, plus http. With the help of the client package, you can
make an HTTP request.
Here is the code below in Python:
import http.client
connection = http.client.HTTPConnection("www.facebook.com") #hostaddress
conn.request("POST", "/") # requestmethod and resource path
response = connection.getresponse() # Gets a response
print(response.status, response.reason)# Replies with status code and description
content = response.read()
Conclusion
Thank you for making it through to the end of Learn Python Programming
! Let’s hope it was informative and able to provide you with all of the tools
you need to achieve your goals—whatever they may be.
The next step is to get practice with Python in detail. Remember that
programming is not an easy job. You need to master basics and use them to
build a house of knowledge that is well-structured and organized. You may
often get irritated with errors. However, always motivate yourself to work
hard. Try to utilize internet resources like stack overflow for increasing
your productivity if you are struck with any code.
Python is a great programming language for beginners due to its extensive
resources and projects in GitHub for beginners. Try to contribute back to
the Python community with all of your strength. Now, go program!
SQL
Introduction
Chapter 1: What is SQL?
What are Databases?
What is a DBMS (Data Management System)?
Types of DBMS
Advantages of Databases
Getting ready to code
Installing MySQL applications
Type of SQL server software versions:
What are the components that are in SQL software?
What to consider before installing the software?
Starting and Stopping Oracle database instances
Writing the First MySQL code
Administrate the database
Object explorer
Creating databases
Modify tables
Manage tables
Delete tables
Schema creation
Creating Data
Inserting data
Chapter 2: SQL Server and Database Data Types
Chapter 3: Creating Your First Database And Table
Step 1: SQL Server Management Studio Software Installation
Step 2: Launch the SQL Studio
Step 3: Identify Database Folder
Step 4: Create a New Database
Step 6: Developing the Primary Key
Step 7: Structure the Tables
Step 8: Creating Other Columns
Step 9: Saving the Table
Step 10: Add Data
Step 11: Running the Table
Step 12: Data Querying
Chapter 4: Creating Your First Database and Table Using Command
Line
Chapter 5: SQL Views and Transactions
Chapter 6: A Look at Queries
Chapter 7: SQL Tools and Strategies
Working with the Queries
Working with the SELECT Command
A Look at Case Sensitivity
Chapter 8: Exercises, Projects And Applications
Examples of Exercises in SQL
Projects in SQL Programming
Applications of SQL
Data Integration
Analytical Queries
Data Retrieval
Chapter 9: Common Rookie Mistakes
DATEADD ( datepart, number, date)
DATEDIFF Function
Datename Function
Chapter 10: Tables
Create tables
Deleting Tables
Inserting Data into a Table
Dropping a Table
Using the ALTER TABLE Query
Chapter 11: The Database
Chapter 12: Tips and tricks of SQL
Four Tips That Make Using SQL Easier!
Chapter 13: Database Components
Database Tables
Rows and NULL values
Primary Keys
Foreign Keys
Stored Procedures
Chapter 14: Working With Subqueries
The SQL Server Subquery
Creating New Databases in SQL Programming
Industries That Use SQL Programming
Common SQL Database Systems
The Relevance of the Database System to Social Networks
Conclusion
Introduction
SQL is a programming language that stands for ‘Structured Query
Language,’ and it is a simple language to learn considering it will allow
interaction to occur between the different databases that are in the same
system. This database system first came out in the 70s, but when IBM came
out with its own prototype of this programming language, then it really
started to see a growth in popularity and the business world started to take
notice.
The version of SQL that was originally used by IBM, known back then as
ORACLE, was so successful that the team behind it eventually left IBM
and became its own company. ORACLE, thanks to how it can work with
SQL, is still one of the leaders in programming languages and it is always
changing so that it can keep up with everything that is needed in the
programming and database management world.
The SQL is a set of instructions that you can use to interact with your
relational database. While there are a lot of languages that you can use to do
this, SQL is the only language that most databases can understand.
Whenever you are ready to interact with one of these databases, the
software can go in and translate the commands that you are given, whether
you are giving them in form entries or mouse clicks. These will be
translated into SQL statements that the database will already be able to
interpret.
If you have ever worked with a software program that is database driven,
then it is likely that you have used some form of SQL in the past. It is likely
that you didn't even know that you were doing this though. For example,
there are a lot of dynamic web pages that are database driven. These will
take some user input from the forms and clicks that you are making and
then will use this information to compose a SQL query. This query will then
go through and retrieve the information from the database to perform the
action, such as switch over to a new page.
To illustrate how this works, think about a simple online catalog that allows
you to search. The search page will often contain a form that will just have
a text box. You can enter the name of the item that you would like to search
using the form and then you would simply need to click on the search
button. As soon as you click on the search button, the web server will go
through and search through the database to find anything related to that
search term. It will bring those back to create a new web page that will go
along with your specific request.
For those who have not spent that much time at all learning a programming
language and who would not consider themselves programmers, the
commands that you would use in SQL are not too hard to learn. Commands
in SQL are all designed with a syntax that fits in with the English language.
At first, this will seem really complicated, and you may be worried about
how much work it will be to get it set up. But when you start to work on a
few codes, you will find that it is not actually that hard to work with. Often,
just reading out the SQL statement will help you to figure out what the
command will do. Take a look at the code below:
How this works with your database
If you decide that SQL is the language that you will work on for managing
your database, you can take a look at the database. You will notice that
when you look at this, you are basically just looking at groups of
information. Some people will consider these to be organizational
mechanisms that will be used to store information that you, as the user, can
look at later on, and it can do this as effectively as possible. There are a ton
of things that SQL can help you with when it comes to managing your
database, and you will see some great results.
Chapter 1 What is SQL?
Databases are an important part of computer technology that has expanded
in wide growth from the past few decades. Every internet or web
application consists of data that needs to be shown and collected. A lot of
technologies nowadays need to store bundles of information and process
them according to user needs within very less time (In microseconds).
What are Databases?
If you need to express a layman definition about a database then here it is
for your understanding.
" Database is something that the stores information which is canonically
known as data. Data may be of any kind. For example, image, text, and
video to name a few."
A practical example of a database:
Consider a library. They usually consist of books and people come to Loan
books. Libraries in the world days used to create bundles of registers to
track the books that are Loaned by the civilians. However, after the advent
of computers things became easier with Libraries getting equipped with
Library management systems. This software usually stores every detail of
the book, Library members and details about the books that are on hold. All
of this information is stored in the databases in the cloud and Library
members can easily access their Library account online with encrypted
safety.
Small Exercise:
I hope you got a good overview of the databases. You will notice how
important they are in the present technological world.
What is a DBMS (Data Management System)?
We usually have data that is sensitive in the databases and there need to be
some regulations to easily and logically manipulate this data with the help
of a system. For this reason, years back computer scientists designed
Database management systems to manipulate, create and erase the data.
With DBMS systems we usually achieve complete authority of the data we
possess and can use them logically.
Types of DBMS
There are various types of DBMS technologies that flourished in the
computer arena in the past decades such as Hierarchal and Network DBMS.
However, they did not prove to be feasible for many reasons. The most
successful database management system is Relation DBMS which
represents the data using Tables. More advanced applications use Object-
oriented DBMS to process the information. However, this book technically
deals with Relational DBMS.
Advantages of Databases
As said before databases are everywhere in the real world nowadays and
have increased their capabilities tremendously. Even smartphones inbuilt
databases to store information and use them for applications. A lot of travel
sources such as Railways, Airlines extensively depend on databases to
categorically obtain real-time information. Databases are also stored on the
internet as a cloud and can decrease costs for small companies. A lot of
multinational companies like Google, Amazon collect tons of information
and store them in remote databases to test and develop machine learning
algorithms.
Just like programming languages databases need a language to effectively
query and update information in the databases. For this exact purpose,
Database query languages are developedWhat are Database Query
Languages?
There is no use of data that cannot be used and manipulated. For this exact
purpose, Database query languages are developed. They usually use two
principle concepts known as Data definition language (DDL) and Data
Manipulation Language ( DML) to query and update the information. The
most popular and preferred database query language is SQL which this
book deals about.
Getting ready to code
Just like any other programming language you need to understand the
essence of the language you are trying to learn before diving into it. Make a
clear note about the advantages of SQL and note down common errors that
you may get encountered with.
Make a list of necessary applications to be installed and check system
requirements for all of that software.
Installing MySQL applications
MySQL is one of the tools that Microsoft offers for countless organizations
and small businesses. There are several costly certification courses
available for a better understanding of the management of these databases.
Here in this book we coherently explain to you the installation procedure
after explaining the types of SQL Server editions that are available.
Type of SQL server software versions:
Microsoft offers a wide range of software availabilities for better
deployment of the services. It is useless to buy huge resources if there is no
enough data. It also doesn’t make sense to rely on fewer resources for huge
data as there will be continuous downtime which may irritate your service
users. For this exact reason, MySQL is available in different types as
described below.
a) Express
This is a small comprehensive edition where it consists of simple resources
and workbench tools that are needed to start running for an individual or a
small enterprise.
b)Standard
Standard version is usually recommended for small business that has
moderate data to be handled. It can quickly monitor the operations and
processes data faster when compared with the express edition
c)Enterprise
Enterprise version is one of the most used SQL servers all around the
world. It has a wide range of capabilities and can be used by moth medium
and large companies. It consists of a lot of services such as reporting,
analysis, and auditing. Enterprise version costs a lot more than the normal
versions due to its complex nature.
d)Developer
This version of the SQL server is especially used by developers to test and
manipulate the functionalities in an environment. All the developers use this
version to experiment with the logical entity they are dealing with. You can
easily convert the license of your developer version to an enterprise version
with a click
e)Web
This version of the SQL server is primarily developed to deal with web
applications. A lot of medium hosting services use this version to store
small amounts of data.
What are the components that are in SQL software?
SQL Server software consists of various components that need to be
installed. Here are some of the most used SQL server managers.
a) Server management system
This is the most important component where every server that is present is
registered, created, managed or erased if needed. This is a working interface
for database administrators to interact with the databases that are operating.
b) Server configuration manager
This component helps us to give customized information about network
protocols and parameters in detail.
c)SQL Server profiler
This is the component that helps you monitor all the activities that are
running through the system.
What to consider before installing the software?
1. Do thorough research about the software you are installing. You can
further refer to the documentation or online resources to check minimum
system requirements and components information.
2. Learn about components. Get a good understanding of different
components such as analysis, reporting that SQL enterprise version offers.
Nowadays many industries must analyze and report the findings as a
database administrator.
3. Learn about authentication modes that are present and do good research
about them.
Starting and Stopping Oracle database instances
The process of starting an Oracle database instance is divided into three
steps: starting the instance, loading the database, and opening the database.
Users can start the database in different modes according to actual needs.
An Oracle database instance must read an initialization parameter file at
startup to obtain parameter configuration information about the instance
startup. If the pfile parameter is not specified in the startup statement,
Oracle first reads the server initialization parameter file spfile at the default
location. If no default server initialization parameter file is found, the text
initialization parameter file at the default location will be read.
The following will explain several STARTUP modes listed in startup syntax
respectively.
1.NOMOUNT model
The code and running results are as follows:
SQL> connect system/sample instance as connect;
2.MOUNT mode
This mode starts the instance, loads the database, and keeps the database
closed.
When starting the database instance to MOUNT mode, the code and
running results are as follows.
SQL> shutdown {Enter the condition}
3.OPEN mode
This mode starts the instance, loads and opens the database, which is the
normal startup mode. Users who want to perform various operations on the
database must start the database instance using OPEN mode.
Start the database instance to OPEN mode, and the code and running results
are as follows.
SQL> startup
Like starting a database instance, shutting down the database instance is
also divided into three steps, namely shutting down the database,
uninstalling the database, and shutting down the Oracle instance.
The SQL statement for the shutdown is here:
SHUTDOWN [Enter the parameter here]
1.NORMAL approach
This method is called a normal shutdown. If there is no limit on the time to
shut down the database, it is usually used to shut down the database.
The code and running results are as follows:
SQL> shutdown normal;
Database shutdowns immediately with the syntax.
2.TRANSACTIONAL approach
This method is called transaction closing. Its primary task is to ensure that
all current active transactions can be committed and shut down the database
in the shortest possible time.
3.ABORT mode
This method is called the termination closing method, which is mandatory
and destructive. Using this method will force any database operation to be
interrupted, which may lose some data information and affect the integrity
of the database. Apart from using the database because it cannot be shut
down using the other three methods, this method should be avoided as
much as possible
Launching MySQL workbench
MySQL Workbench is a visual database design software released by
MySQL AB; whose predecessor was DB Designer of FabForce. MySQL
Workbench is a unified visualization tool designed for developers, DBA
and database architects. It provides advanced data modeling, flexible SQL
editor and comprehensive management tools. It Can be used on Windows,
Linux, and Mac.
To use it in windows, click on the SQL server studio and select the option
workbench to open the interface. If you are using Linux and Mac you need
to enter the command ‘workbench’ after entering into the SQL instance.
Writing the First MySQL code
First of all, when you are trying to write your first MySQL code it is
important to get a good text editor for writing down the queries. SQL
Software's provide query writing tools for its users usually. It is important to
learn about syntax in detail. The first written code is always clumsy and can
easily make you lose patience. However, remember that there is a lot to
learn before actually making things better with your code.
Definition of Database
This chapter is a clear introduction to the usage of the SQL management
server and performing different operations for the system characteristics.
We will start with creating tables and travel till creating triggers using the
SQL server management studio. This chapter is pretty straightforward and
will introduce you to the interfaces that SQL software offers. As we move
on further, we will discuss various advanced SQL query statements using
Data definition and data manipulation languages. For now, let us learn
about all the capabilities of the SQL server management system.
The server management system consists of all the servers listed on the
instance and we need to click on the server we are willing to work with.
When we click on the server it will ask authorization details. Authentication
is important for the security of databases. So, unless you give the correct
credentials you will not be able to connect to the server and all the
databases it possesses.
Administrate the database
After connecting to the database, you have full control over the data that is
present. You can look at all the objects for a particular database using the
object explorer. If your server is not registered you need to register your
server with Microsoft for making it work for the first time. Administration
capabilities will also give you the power to change the authentication details
of the database.
Object explorer
Object Explorer is a tree view of all the instances and entities that are
present. They are placed hierarchically and it is easy to operate the
databases in that way. You can even connect to multiple databases with the
help of an object explorer that is present. Object Explorer is one of the
friendliest user interfaces in the SQL server studio.
Create new server groups
Usually, SQL offers users to create groups with the databases present. You
can also provide permissions to particular users to access the database. In
advanced application systems, this is replaced with encrypted key
authentication.
Start and stop servers
You can easily start or stop databases present using the options available for
the instances. All you need to do is to press the stop button to end the
database initiation.
Creating databases
First of all, go to the object explorer and select the server you wish for.
After getting authenticated click on the lift pane and it will give a list of
options. In those options select ‘create a new database’ to create a database
instance. You can even select object properties and change some of the
information manually. For example, you can input data type information.
You can even provide the number of rows and columns for the databases.
After clicking the create button on the interface the changes will take place
immediately.
Modify tables
You can easily change the number of columns in the table using the SQL
server management studio. The object pane offers an option called as
modify. You can change all the properties of the database and it will take
change immediately within split seconds.
With this modification option, you can change the primary key and foreign
key values so that you can do complex queries.
Manage tables
Management is altogether a different option in the SQL server software.
When you click on the manage instance all the properties will be displayed.
You can look at all the data values and types available and can change them.
For example, you can change the length of the columns and change the data
type of a column from decimal to integer. Everything happens in a single
click.
You can even see the ER diagram of the databases to understand the
relationship between the entities and instances.
Delete tables
Deleting also works in the same way as managing and creating. First of all,
select the table you are looking forward to delete. Right-click on the table
and click on the delete instance option. After entering the option, you will
get a prompt to whether delete or not. If you click yes then all the data in
that table will be deleted at an instance. It is not possible to restore the
deleted columns from SQL server management software. However, you can
restore the deleted tables using recovery models available in the SQL
server.
Schema creation
Schema is a set of instructions that the database possesses. People usually
get confused with the term schema but it is simply a customized database. It
is always recommended to create a schema because you will be well aware
of the options in the instance. Schema creation is a good practice for
database administrators.
To create a schema all you need to do is enter the database objects and click
on the option that says create a schema. When you click this option all of
the properties of the column will be given and you need to manually enter
them. This is how a schema is created and there are even options in the
interface to delete that schema.
Creating Data
Entering data into the database or table is one of the most important
understanding all database administrators should be aware of. To create data
using the SQL server you need to start understanding the essence of the
system.
All you need to do is enter the option to create data and fill it with column
values of your choice. You can even create data belonging to different data
types using this functionality.
Inserting data
Data should be inserted to go on with the queries. It is usually not possible
to huge data from the SQL server software because of the complexities that
may arise. However, if you are reluctant to insert data then we will explain
an easy way.
First of all, create an excel document and fill the values in the columns. Use
this file and click on the insert data option present in the sideline of the
database option. After that, all of the values will be inserted and can be
easily updated with other available options.
This chapter is just a small introduction to the SQL server software. We
have potentially introduced some of the concepts that databases usually deal
with.
Chapter 2 SQL Server and Database Data
Types
To be able to hold data in certain columns, SQL Server and other relational
database management systems utilize what are called “data types.”
There are different data types available, depending on what data you plan to
store.
For instance, you may be storing currency values, a product number and a
product description. There are certain data types that should be used to store
that information.
The majority of the data types between each RDBMS are relatively the
same, though their names differ slightly, like between SQL Server and
MySQL. There are a lot of data types, though some are more frequently
used than others. The following is a list of common ones that you may find
or work with.
The AdventureWorks2012 database will be used as an example.
VARCHAR
This is an alphanumeric data type, great for holding strings like first and
last names, as well as an email address for example. You can specify the
length of your varchar data type like so when creating a table,
VARCHAR(n). The value of ‘n’ can be anywhere from 1 to 8,000 or you
can substitute MAX, which is 2 to the 31st power, minus 1. However, this
length is rarely used.
When designing your tables, estimate the length of the longest string plus a
few bytes to be on the safe side. If you know that the strings you will be
storing will be around 30 characters, you may want to specify
VARCHAR(40) to be on the safe side.
This data type is flexible in a sense to where it will fit only the characters
entered into it, even if you don’t insert 40 characters like in the example
above.
However, there is a bit of overhead with storage, as it will add 2 bytes to
your entire string. For instance, if your string is 10 bytes/characters in
length, then it will be 12 in all actuality.
NVARCHAR
Much like the varchar data type, this is alphanumeric as well. However, it
also stores international characters. So this is a good option if you end up
using characters and letters from another country’s language.
The other difference between VARCHAR and NVCARCHAR is that
NVARCHAR’s values go up to 4,000 instead of 8,000 like VARCHAR.
Though they are the same in how they are defined in length like so:
NVARCHAR(n) where ‘n’ is the length of characters.
EXACT NUMERICS
There are various number data types that can be used to represent numbers
in the database. These are called exact numbers.
These types are commonly used when creating ID’s in the database, like an
Employee ID for instance.
Bigint – Values range from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807, which isn’t used so frequently.
Int – most commonly used data type and its values range from
-2,147,483,648 to 2,147,483,647
Smallint – Values range from -32,768 to 32,767
Tinyint – Values range from 0 to 255
In any case, it’s best to pick the data type that will be the smallest out of all
of them so that you can save space in your database.
DECIMAL
Much like the exact numeric data types, this holds numbers; however, they
are numbers including decimals. This is a great option when dealing with
certain numbers, like weight or money. Decimal values can only hold up to
38 digits, including the decimal points.
Let’s say that you wanted to enter $1,000.50 into your database. First, you
would change this value to 1000.50 and not try to add it with the dollar sign
and comma. The proper way to define this value per the data type would be
DECIMAL(6,2).
FLOAT
However, this is more of an Approximate Numeric, meaning it should not
be used for values that you do not expect to be exact. One example is that
they are used in scientific equations and applications.
The maximum length of digits that can be held within a column while using
this data type is 128. Though, it uses scientific notation and its range is
from -1.79E + 308 to 1.79E + 308. The “E” represents an exponential value.
In this case, its lowest value is -1.79 to the 308th power. Its max value is
1.79 to the 308th power (notice how this is in the positive range now).
To specify a float data type when creating a table, you’d simply specify the
name of your column and then use FLOAT. There is no need to specify a
length with this data type, as it’s already handled by the database engine
itself.
DATE
The DATE data type in SQL Server is used quite often for storing dates of
course. Its format is YYYY-MM-DD. This data type will only show the
month, day and year and is useful if you only need to see that type of
information aside from the time.
The values of the date data type range from ‘0001-01-01’ to ‘9999-12-31’.
So, you have a lot of date ranges to be able to work with!
When creating a table with a date data type, there’s no need to specify any
parameters. Simply inputting DATE will do.
DATETIME
This is similar to the DATE data type, but more in-depth, as this includes
time. The time is denoted in seconds; more specifically it is accurate by
0.00333 seconds.
Its format is as follows YYYY-MM-DD HH:MI:SS. The values of this data
type range between '1000-01-01 00:00:00' and '9999-12-31 23:59:59'.
Just as the DATE data type, there is no value or length specification needed
for this when creating a table. Simply adding DATETIME will suffice.
If you’re building a table and are deciding between these two data types,
there isn’t much overhead between either. Though, you should determine
whether or not you need the times or would like the times in there. If so,
then use the DATETIME data type, and if not, use the DATE data type.
BIT
This is an integer value that can either be 0, 1 or NULL. It’s a relatively
small data type in which it doesn’t take up much space (8 bit columns = 1
byte in the database). The integer value of 1 equates to TRUE and 0 equates
to FALSE, which is a great option if you only have true/false values in a
column.
Chapter 3 Creating Your First Database And
Table
Finally, use the syntax below to retrieve desired data from the underlying
table “items” to confirm if the “DELET” statement in fact removed the
record:
"SELECT
*
FROM
items;"
The “result set” is displayed in the picture below, which confirms that the
row with “id value 3” was deleted from the “items” table:
Now, assume that you would like to insert the “jobtitle” column to the
“contacts view”. You can accomplish this with the syntax below:
"CREATE OR REPLACE VIEW contacts AS
SELECT
firstName,
lastName,
extension,
email,
jobtitle
FROM
employees;"
The “result set” is displayed in the picture below:
Dropping a “SQL View”
The “DROP VIEW” statement can be utilized to delete an existing view
from the database, using the syntax below:
"DROP VIEW [IF EXISTS] [database_name].[view_name]"
The "IF EXISTS" clause is not mandatory in the statement above and is
used to determine if the view already exists in the database. It prevents you
from mistakenly removing a view that does not exists in the database.
You may, for instance, use the "DROP VIEW" statement as shown in the
syntax below to delete the "organization" view:
"DROP VIEW IF EXISTS organization;"
SQL TRANSACTIONS
A transaction can be defined as "a unit of work that is performed against a
database". They are “units or work sequences” that are performed in a
“logical order”, either manually by a user or automatically using by
the database program.
Or simply put, they are “the spread of one or more database modifications”.
For instance, if you create a row, update a row, or delete a row from the
table, that means you are executing a transaction on that table. To maintain
data integrity and address database errors, it is essential to regulate these
transactions.
Basically, to execute a transaction, you must group several SQL queries and
run them at the same time.
Properties of Transactions
The fundamental properties of a transaction can be defined using the
acronym “ACID” for the properties listed below:
Atomicity − guarantees successful completion of all
operations grouped in the work unit. Or else, at the point of
failure, the transaction will be aborted and all prior
operations will be rolled back to their original state.
Consistency − makes sure that when a transaction is properly
committed, the database states are also correctly updated.
Isolation − allows independent and transparent execution of
the transactions.
Durability − makes sure that in case of a system
malfunction, the outcome or impact of a committed
transaction continues to exist.
To explain this concept in greater detail, consider the steps below for
addition of a new sales order in the “MySQL sample database”:
Now, to select the backup file as shown in the picture below, “select the
device radio button and click on the ellipse”.
Next, click Ok and the window shown below will be displayed to you.
Now, from the “top-left corner of the screen select the Files option”, as
shown in the picture below:
Lastly, select “Options” from the “top-left corner of your screen” and click
“OK” to restore the “TestDB” database, as depicted in the picture below:
Chapter 6 A Look at Queries
While we have spent a little bit of time taking a look at some of the
commands and queries that we are able to use when it comes to working in
the SQL language, it is time for us to go more in-depth about these queries
and what they are able to do for some of our needs along the way as well.
When we are working on our own business database and it is all set up the
way that we would like, it is going to be possible that at one point or
another you will want to do a search in order to make sure you are able to
find the perfect information inside of all that. This is going to make it easier
for us to find the easier information and results that we want. But we do
have to make sure that the database is set up in the right manner so that we
can use the right commands, and see that it is fast and accurate in the
process.
Think of this like when someone comes to your website, searching for that
particular product that they would like to purchase. Do you want them to
get stuck on the website that is slow, and have them see results that have
nothing to do with the item they wanted? Or would you like a fast search
that was helpful and will encourage the person to make that purchase? Of
course, for the success of your business, you are more likely to want the
second option, and we can take a look at how to set up your database and
work with queries in order to make this happen.
Chapter 7 SQL Tools and Strategies
Server management is an essential practice that helps administrators and
programmers to ensure that the database infrastructure performs optimally.
Various SQL tools are used for this purpose. These SQL tools enable
programmers and Database Administrators to perform their roles efficiently
and perfectly. It's vital to note that the database environment is ever-
changing. In this regard, the tools enable the Database Administrators and
programmers to update any changes in SQL databases. To manage the
database infrastructure, SQL database administrators and programmers
apply various tools. The objective of this topic is to examine various
methods of installing and updating SQL server tools, the various features,
and enhancements of new SSMS, kinds of SQL data tools, and the tools
which are used to develop R-code.
Complete support for processes - the tool has full support for
various procedures including standard transactions, many
access ways, support for incremental backups and others.
Application of complex technology - the tool applies the
latest technology like FB25 and FB30. This means that it
offers high-quality services.
Support of cloud - The tool recognizes cloud infrastructure.
Squirrel SQL
This tool supports the management of Java databases. Through this tool,
you can view the SQL database and provide commands. The tool works on
different databases, including IBM, SQL, Oracle, and others. Its key
features include:
The name of the table or column must start with a letter, then
it can be followed by a number, an underscore, or another
letter. It’s preferable that the number of the characters does
not exceed 30.
You can also use a VARCHAR (variable-length character)
data type to help create the column.
Common data types are:
date – date specified or value
number (size) – you should specify the maximum
number of column digits inside the open and close
parentheses
char (size) – you should specify the size of the fixed
length inside the open and close parentheses.
varchar (size) – you should specify the maximum size
inside the open and close parentheses. This is for
variable lengths of the entries.
Number (size, d) – This is similar to number (size),
except that ‘d’ represents the maximum number of
digits (from the decimal point) to the right of the
number.
Hence if you want your column to show 10.21, your date type would be:
number (2,2)
Example: CREATE TABLE traffic_hs2064
(country varchar (40),
keywords varchar (30),
time number (3),
post varchar (40) );
Step #5 – Add CONSTRAINTS, if any
CONSTRAINTS are rules that are applied for a particular column. You can
add CONSTRAINTS, if you wish. The most common CONSTRAINTS are:
If your base table is the table above, and you want to add another column
labeled City, you can create your SQL query this way:
Examples: ALTER TABLE Traffic_hs2064
ADD City char(30);
You can also ALTER a table to ADD a constraint such as, NOT NULL.
Example: ALTER TABLE Traffic_hs2064
MODIFY City datatype NOT NULL;
This will modify all entries that are NOT NULL.
You can also ALTER TABLE to DROP COLUMNS such as, the example
below:
Example: ALTER TABLE Traffic_hs2064 DROP COLUMN Time;
Using the second table with this SQL query, the resulting table will be this:
Traffic_hs2064
Country Searchword Post City
America perfect Matchmaker NULL
Italy partner NatureTripping NULL
Sweden mate Fiction NULL
Spain couple News NULL
Malaysia team Health NULL
Philippines island Entertainment NULL
Africa lover Opinion NULL
NOT NULL
This constraint indicates that the NOT NULL values should not be present
in the columns of a stored table.
CHECK
This will ensure that all parameters have values that have met the criteria.
UNIQUE
This ascertains that all values in the columns are distinct or unique.
PRIMARY KEY
This indicates that the values in two or more columns are NOT NULL and
simultaneously UNIQUE.
FOREIGN KEY
This will ascertain that the values of columns from different tables match.
DEFAULT
There is a specified DEFAULT value for columns. This may appear as
blanks or appear as NULL.
Make sure you use these constraints properly to make the most out of your
SQL queries.
Chapter 11 The Database
A database is an assortment of data that is sorted out, so it tends to be
effectively gotten to, oversaw, and refreshed. PC databases commonly
contain accumulations of information records or documents containing data
about deals exchanges or associations with explicit clients.
In a relational database, computerized data about a particular client is
composed of lines, sections, and some of the tables that we decide to file to
make it easier to find the data that is the most pertinent to our work.
Something that is interesting here is that the graph database is going to
work with edges and hubs to help us make those connections and
characterize them between information sections and the inquiries, and this
is going to require that we work with semantic inquiry punctuation.
There are also a few options that are going to offer us Corrosive
consistency, which include strength, detachment, consistency, and
atomicity, to help ensure that the information we see is reliable and that
some of the exchanges we work with are finished.
Different Types of Databases
There have been a lot of advancements when it comes to databases through
the years. There are different levels and system databases, and today we get
to work with ones that are more object-oriented and ones based on the cloud
or SQL.
In one view, it is possible that the databases are going to be grouped by the
kind of content that they hold onto, which can make it easier for us to work
with them and find the one that we need. In figuring, databases are, in some
cases, arranged by their hierarchical methodology.
One thing that we are going to notice when we work with this part is that
there will be many different types of databases that we are able to work
with, starting with the relational database that we work with, all the way to
a distributed database, the cloud database, the NoSQL database, and the
graph database as well. Let’s take a look at how each one is going to work.
First is the relational database. This is going to be one that was designed in
1970, and it is considered one of the best options to work with for many
businesses. It will hold onto lots of tables that will place the information
you want into some of the predefined classes. And each of these tables in
the database is going to have one information classification in a segment,
and each line is going to have the right segments as well.
This kind of database is going to rely on the SQL language that we have
been talking about so far. This is going to be one of the standard client and
application program interfaces for this kind of database. And because of the
features and more that we are going to find with some of the relational
databases, you will find that it is easy to create and work with and that it
will be able to handle a lot of the great parts that you want in the process.
In addition to working with a relational database, we are able to work with
the distributed database, which is a little bit different. This is going to be a
type of database where the segments are going to be put into physical areas,
and then it will be prepared to be repeated or scattering among various
focuses on the system.
You can choose whether to make this database type heterogeneous or
homogenous. All of the physical areas that are found in one of these that is
more homogenous will have the equivalent basic equipment and will run
the right frameworks that you need in order to handle the database
application.
Another thing to consider here is that the equipment and the database
applications that are in one of the heterogenous option could be diverse in
all of the areas that we are working with. This helps us to get the
information in the right places as we go.
The next kind of database that we want to work with is the cloud database.
This is going to be a database that has been improved or worked on for the
virtualized domain. This is going to either be half of a cloud, a private
cloud, or it could be open cloud as well.
This kind of database is important because it is going to provide you with a
ton of advantages. For example, you can pay for the amount of transfer
speed and the capacity limit that you are looking for on each of the
utilizations that you want along the way, and they are going to provide us
with a lot of the versatility that we need for any kind of the databases that
we want to work with.
In addition to all of this, we will find that the cloud database is going to
offer us some undertakings the chances to handle applications of a business
type as a product of the administration and what it wants to see. And it is
going to store that information as you need it, without pushing it onto your
own servers along the way.
Next on the list is going to be the NoSQL database. These are going to be a
good database that you can work with, the ones that are valuable for some
really big arrangements when you want to distribute your information.
These databases are going to be good when you would like to get
information execution that is going to give us that the relational databases
are not able to handle.
These kinds are going to be the best when the company using them has to
take a bunch of information that is unstructured or information that has
been saved in a lot of virtual servers, and we need to analyze it.
We can also work with some of the object-oriented databases along the way
as well. Things that are made when it comes to utilizing object-oriented
programming languages are going to be put away into some of the
relational databases, but these are going to be the right kinds of databases
that we need.
For example, a sight and sound record in our relational databases could end
up as an information object that is quantifiable, rather than working with
one that is more alphanumeric.
Then there is the graph database as well. This kind of database is going to
be graph-oriented, is going to be similar to the NoSQL database that will
work with the graph hypotheses in order to store, guide, and then query any
of the connections that we need. The best way for us to think about this
kind of database is that it is a big assortment of edges and hubs, and all of
the hubs are going to speak to one of the elements, and then the edges are
going to speak back to the association that will happen between those hubs.
These graph databases are often not used as much as the others, but they are
starting to come into popularity thanks to how they can help with breaking
down some of the interconnections that are there.
For example, it is not uncommon for a company to utilize a graph database
to help mind information that pertains to their clients from some of the
work they do online. It is also common for this kind of database to utilize a
language that is known as SPARQL. This language is a bit different, but it
allows us to examine graphs and the databases that use them a bit more.
Creating a Database with SQL
Under Unix, database names are case-touchy (not at all like SQL
watchwords), so you should consistently allude to your database as the
zoological display, not as Zoo, Zoo, or some other variation. This is
likewise valid for table names. (Under Windows, this confinement doesn't
have any significant bearing, despite the fact that you should allude to
databases and tables utilizing the equivalent letter case all through a given
query. In any case, for an assortment of reasons, the prescribed best practice
is consistently to utilize the equivalent letter case that was utilized when the
database was made.)
Making a database doesn't choose it for use; you should do that
unequivocally. To make the zoological display the present database, utilize
this announcement:
Your database should be made just once, yet you should choose it to utilize
each time you start a MySQL session. You can do this by giving a
Utilization articulation as appeared in the model. On the other hand, you
can choose the database on the direct line when you summon MySQL.
Simply indicate its name after any association parameters that you may
need to give.
Removing a database with SQL
With the SQL Server The executive's Studio, you can right tap on the
database and select "Erase."
In the erase object window, select the choice "Erase reinforcement and
reestablish history data for databases" in the event that you need to evacuate
this data.
On the off chance that you need to kick out open associations with your
database, select the "Nearby existing associations." It will be difficult to
expel the database on the off chance that you don't choose the last choice,
and there are as yet open associations with your database. You will get a
mistake that the database is still being used and can't be erased
When you hit the alright catch, the database will be evacuated off the SQL
example, and the database documents on the operating system level will
likewise be expelled. Unquestionably not important to close down the entire
occurrence to evacuate a database.
Presently after the expulsion, despite everything you have some additional
cleanup stuff to do that individuals regularly overlook…
Erase the occupations
Erase the occupations that were identified with the database. In the event
that you won't expel them, the employments will fall flat, and you will get
pointless alarms.
Erase the reinforcement documents
In the event that you needn't bother with the reinforcement documents any
longer, simply expel them. Be that as it may, I would prescribe to keep the
last full reinforcement of the database and file it for in any event a year or 2.
No one can really tell that someone needs the information later on… ☺
Erase the logins without DB client
Your database had likely some database clients designed that were
connected to a server login.
In the event that that server login isn't utilized for some other database
client and isn't individual from any server job other than open, I would
prescribe to expel that login. For security reasons as well as to keep your
server clean.
Schema Creation with SQL
A client can make any number of schemas. The schema that has been made
has a place with the current client; in any case, it tends to be relegated to
another client or job with the ALTER SCHEMA explanation.
The information volume of the items within a schema can be restricted
using amounts as in the Schema Portion segment.
At the point when you make another schema, you certainly open this new
schema. This implies this new schema is set as the CURRENT_SCHEMA,
and any further items made are within this new schema.
If you have specified the alternative IF NOT EXISTS, at that point, no
mistake message is tossed if a schema with a similar name as of now exists.
Likewise, the specified schema is opened regardless of whether it, as of
now, exists.
The USING choice in a virtual schema specifies the connector UDF
content, which at that point, characterizes the substance of the virtual
schema. Using the WITH condition, you can specify certain properties that
will be utilized by the connector content.
);
Primary Keys
A primary key is a constraint on a column that forces every value in that
column to be unique. By forcing uniqueness on values in that column, it
helps maintain the integrity of the data and helps prevent any future data
issues.
A realistic example of a primary key would be an employee ID or a sales
record ID. You wouldn’t want to have two of the same employee ID’s for
two different people, nor would you want to have two or more of the same
sales record ID’s for different sales transactions. That would be a nightmare
when trying to store and retrieve data!
You can see in the below example that each value for BusinessEntityID is
unique for every person.
Foreign Keys
Another key similar to the primary key is a foreign key. These differ from
primary keys by not always being unique and act as a link between two or
more tables.
Below is an example of a foreign key that exists in the
AdventureWorks2012 database. The foreign key is ProductID in this table
(Sales.SalesOrderDetail):
The ProductID in the above table is linking to the ProductID (primary key)
in the Production.Product table:
Essentially, foreign keys will check its link to the other table to see if that
value exists. If not, then you will end up receiving an error when trying to
insert data into the table where the foreign key is.
Constraints
Primary keys and foreign keys are known as constraints in the database.
Constraints are “rules” that are set in place as far as the types of data that
can be entered. There are several others that are used aside from primary
keys and foreign keys that help maintain the integrity of the data.
UNIQUE – enforces all values in that column to be different. An example
of this could be applied to the Production.Product table. Each product
should be different, since you wouldn’t want to store the same product
name multiple times.
NOT NULL – ensures that no value in that column is NULL. This could
also be applied to the same table as above. In this case, the ProductNumber
cannot have a NULL value, as each Product should have its own
corresponding ProductNumber.
DEFAULT – sets a default value in a column when a value is not provided.
A great example of this would be the ListPrice column. When a value isn’t
specified when being added to this table, the value will default to 0.00. If
this value were to be calculated in another table and be a NULL value (like
a sales table where sales from the company are made), then it would be
impossible to calculate based on a NULL value since it’s not a number.
Using a default value of 0.00 is a better approach.
Stored Procedures
Stored procedures are pre-compiled SQL syntax that can be used over and
over again by executing its name in SQL Server. If there’s a certain query
that you’re running frequently and writing it from scratch or saving the file
somewhere and then opening it to be able to run it, then it may be time to
consider creating a stored procedure out of that query.
Just like with SQL syntax that you’d write from scratch and passing in a
value for your WHERE clause, you can do the same with a stored
procedure. You have the ability to pass in certain values to achieve the end
result that you’re looking for. Though, you don’t always have to pass a
parameter into a stored procedure.
As an example, let’s say that as part of the HR department, you must run a
query once a month to verify which employees are salary and non-salary, in
compliance with labor laws and company policy.
Instead of opening a file frequently or writing the code from scratch, you
can simply call the stored procedure that you saved in the database, to
retrieve the information for you. You would just specify the proper value
(where 1 is TRUE and 0 is FALSE in this case).
EXEC HumanResources.SalariedEmployees @SalariedFlag = 1
In the result set below, you can see some of the employees who work in a
salary type position:
Triggers
A trigger in the database is a stored procedure (pre-compiled code) that will
execute when a certain event happens to a table. Generally, these triggers
will fire off when data is added, updated or deleted from a table.
Below is an example of a trigger that prints a message when a new
department is created in the HumanResources.Department table.
--Creates a notification stating that a new department has been created
--when an INSERT statement is executed against the Department table
CREATE TRIGGER NewDepartment
ON HumanResources.Department
AFTER INSERT
AS RAISERROR ('A new department has been created.', 10, 9)
To expand on this a little more, you specify the name of your trigger after
CREATE TRIGGER. After ON, you’ll specify the table name that this is
associated with.
Next, you can specify which type of action will fire this trigger (you may
also use UPDATE and/or DELETE), which is known as a DML trigger in
this case.
Last, I’m printing a message that a new department has been created and
using some number codes in SQL Server for configuration.
To see this trigger in the works, here’s the INSERT statement I’m using to
create a new department. There are four columns in this table,
DepartmentID, Name, GroupName and ModifiedDate. I’m skipping the
DepartmentID column in the INSERT statement because a new ID is
automatically generated by the database engine.
--Adding a new department to the Department's table
INSERT INTO HumanResources.Department
(Name, GroupName, ModifiedDate)
VALUES
('Business Analysis', 'Research and Development', GETDATE()) --
GETDATE() gets the current date and time, depending on the data type
being used in the table
The trigger will prompt a message after the new record has been
successfully inserted.
A new department has been created.
(1 row(s) affected)
If I were to run a query against this table, I can see that my department was
successfully added as well.
Chapter 14 Working With Subqueries
In SQL programming, a subquery is also referred to as a nested query or an
inner query. Subqueries are defined as queries within other SQL queries.
They are customarily embedded inside the WHERE clause.
The purpose of subqueries is returning data that will be used in the
significant queries as conditions for further restricting of data being
retrieved. Subqueries can be used in coordination with SELECT, INSERT,
UPDATE, and DELETE statements. They can also be used along with
operators such as, IN, =, <=,>=, and BETWEEN.
There are rules that are set to be followed by subqueries. They include;
All subqueries should be enclosed inside parentheses
Each subquery can only contain one column within the SELECT clause.
This is possible unless there are many columns existing in the significant
query for the subqueries to compare their selected columns.
Subqueries that are returning multiple rows can only be used together with
the numerous value operators. Such operators include the IN operator.
The SELECT list must not include any references evaluating to a CLOB,
ARRAY, NCLOB, or BLOB.
It is not possible for subqueries to be enclosed in a set of functions.
It is not applicable for the BETWEEN operator to be used with a subquery.
It is, however, possible for the BETWEEN operator to be used in a
subquery.
In most frequent cases, subqueries are used together with the SELECT
statement. There are also instances when the subqueries are used along with
the INSERT Statements. The INSERT statements make use of the data
returned from the subqueries. This data is used when inserting into other
tables. Data that is selected in the subqueries is modified using different
characters, date, and number functions.
Subqueries are also used in coordination with the UPDATE statements. One
or many columns existing in a table are updated by the use of a subquery
together with the UPDATE statement. Subqueries are also applicable
together with the DELETE statements. In such a case, they are used in
deleting records from existing tables that are no longer valuable. When the
two are used together, they bring about some changes to the existing table’s
columns and rows.
There is no specified syntax for use in subqueries. However, in most cases,
subqueries are used with the SELECT statements as indicated below.
SELECT column_name
FROM table_name
WHERE column_name
Expression operator
(SELECT COLUMN_ NAME from TABLE NAME
WHERE…)
The SQL Server Subquery
It is essential for programmers to understand SQL Server subqueries and
how subqueries are used for querying data. SQL servers help in executing
whole queries. In the case of customers’ tables, it first comes up with lists
of customers’ IDs. It then comes up with substitution of the identification
numbers that are returned by subqueries within the IN operator. It then
engages in executing outer queries to help in getting the final outcomes set.
Using subqueries can help programmers join two or more steps together.
This is because they allow for the elimination of the need to select the
identification numbers of customers and plug them within the outer queries.
Additionally, the questions themselves adjust automatically anytime there
are changes in the customer’s data.
Subqueries can also be nested in other subqueries. SQL programming
servers support over 30 levels of nesting. The SQL server subqueries are
used in place of expressions. When the subqueries return single values, they
are used anywhere expressions are used. SQL server subqueries are used
together with the IN operator. Subqueries used with this operator usually
return zero or more value sets. The outer queries make use of the values that
have been answered by the central subqueries.
SQL server subqueries are also used with the ANY operator. Subqueries
that are introduced using the ANY operators usually have the following
syntax:
Scalar_expression
Comparison_operator ANY
(subquery)
When the subqueries return lists of values such as v1, v2, v3, the ANY
operator statement usually return TRUE if there is a comparison of one pair
and FALSE when it does not. The ALL operator, on the other hand, returns
TRUE in case all the comparisons made pair, and when they do not, it
returns FALSE. THE EXIST operators return TRUE when subqueries
return results, but when they do not, they return FALSE.
Creating New Databases in SQL Programming
When creating a database in SQL programming, the initial queries are
responsible for the creation of new databases. One of the best examples is
the Facebook application. The application contains some databases for all
the following components.
Users- This is a database on Facebook that is used as a storage for every
information on the user’s profile. It stores all the details as the person
uploads them on their accounts.
Interests- The database on Facebook helps in holding various interests of
the user. These interests are applied when tracking down the hobbies and
talents of the users.
Geographic Locations- This is a database that holds every city around the
universe where any user live.
The second query when creating a database is responsible for coming up
with new tables within specific databases.
Industries That Use SQL Programming
SQL programming databases are commonly applied in technological fields
whereby large amounts of data are used. Some of the most common sectors
are the finance, music applications, and social media platforms industries.
In the finance industries, SQL is mainly used in payments processors, and
banking applications. They include Stripe, whereby they operate and store
data involving significant financial transactions as well as users. All these
processes are supported by complex databases. Banking database systems
usually require maximum security. This is, therefore, one of the reasons
why the SQL code applied has the highest levels and capabilities of risk
compliance.
Some of the music applications such as Pandora and Spotify also require
the use of intensive databases. These databases play significant roles
because they help the applications to store large libraries consisting of
music albums and files. The music stored in there is from different artists.
Therefore, these databases are used when finding what users are trying to
look for, storing the data about particular users as well as their preferences,
and interests.
Social media platforms are other industries that commonly use SQL
programming. This is because they require multiple data processing. Some
of the social media apps such as Snapchat, Facebook, and Instagram are
using SQL to enhance the storage of the profile information of their users.
Such information includes biography, location, and interests. SQL is also
applied in these applications to improve efficient updating of the
application’s database anytime a user comes up with some new posts, or
share some photos. It also allows for the recording of messages that are
generally sent from one user to the other. By this, it helps the users to
retrieve the messages posted and reread them in the future.
Common SQL Database Systems
The SQL database systems are typically ranked depending on the DB-
Engines popularity score. Below are some of the variables that are taken
into consideration during the rankings.
The number of time the system has been mentioned on websites. This is
measured in terms of the outcomes in queries on the search engines.
The general interest within the system. This considers how frequently it has
been searched in Google Trends.
The frequency of technical discussions on the particular database system.
The number of job offers through which the database system has been
mentioned.
The number of profiles existing in professional networks whereby the
system has been mentioned.
The Relevance of the Database System to Social Networks
1. Oracle Database
This is the most common SQL database system used all over the world
today. Numerous industries are using it in their operations. It is, however,
commonly used in the processing of online transactions and data
warehousing.
2. MYSQL Database
It is one of the open-source database systems in SQL. It is freely available
to businesses and individuals. Sit is popularly used by small scale
businesses and startups. They commonly use it because it does not have a
license fee. It is also used in multiple applications and software programs
that are open-source in nature.
3. Microsoft SQL Server
The SQL Server is Microsoft’s modified database management system. It is
used in the running on all main versions of the Windows operating systems.
It is also used in the consumer software and web servers running on
Windows. This means that the Microsoft SQL server has an extensive user
base.
4. POSTGRESQL
It is also a free open source database system. It is commonly used in
multiple industries due to free license models.
Conclusion
As mentioned above, SQL is used in different sectors globally and applied
in different areas to help in data management. One of them includes index
structures modifications that encompass the creation of pathways that helps
in the collection of data that quickly trace information of interest. SQL can
also be applied as a technique to modify and change database tables. That
is, it helps in keeping the data stored up to date, therefore, eliminating
instances of outdated data, which are often misleading.