Visual Basic With SQL Server
Visual Basic With SQL Server
VISUAL BASIC
WITH
SQL SERVER
It has powerful database access tools, by which you can easily develop front end applications.
o It also supports ActiveX technology, in which you can access the features of other application in
system application. For example: Microsoft Word, Microsoft Excel, etc.
RAD Problems
Let us discuss the major problems with VB 6.0, which has been creating troubles for VB developers for a
long time.
No capabilities for multithreading.
Lack of implementation inheritance and other object oriented features.
Poor error handling capabilities.
Poor integration with other languages such as C++.
No effective user interface for Internet based applications.
https://www.visualstudio.com/downloads
Step 2. As clicked on download link, it starts downloading an .exe file, as shown in the image below.
Step 3. Click on the .exe file and then, it shows a pop-up window.
Step 6. After clicking on Continue, Visual Studio will start downloading its initial files as shown in the
image below.
Step 8. After clicking on install button, your Visual Studio IDE will start downloading and then it displays
the screen, as we have shown below.
Step 9. From the above image, select .NET desktop development and click on install open which may
take some time to download the Visual Studio in your system, as shown in below image.
Step 11. Click on Launch button, and then it shows the below image in your screen that represents Visual
Studio has been successfully launched in your machine.
And then it shows a below screen to select the Visual Studio theme. By default, it takes Blue theme, and
if you want to change, you can easily change the Visual Studio theme by clicking on other themes.
Step 13. After click on Create a new project, it shows the below screen to choose what type of
application you are going to build in Visual studio. In this you can select the Console based application or
Window Form Based application, as shown in below image. Here we chose the Console based application,
and then click on the Next button.
Step 14. When you click the Next button, it shows the below image to define the project name, and also
reminds if you want to place the solution and project in the same directory.
This image shows Visual Studio with an open project and several key tool windows you'll likely use:
Solution Explorer (top right) lets you view, navigate, and manage your code files. Solution Ex-
plorer can help organize your code by grouping the files into solutions and projects.
The editor window (center), where you'll likely spend a majority of your time, displays file contents.
This is where you can edit code or design a user interface such as a window with buttons and text
boxes.
The Output window (bottom center) is where Visual Studio sends notifications such as debugging and
error messages, compiler warnings, publishing status messages, and more. Each message source has
its own tab.
Team Explorer (bottom right) lets you track work items and share code with others using version
control technologies such as Git and Team Foundation Version Control (TFVC).
VB REFERENCE RESOURCES
Using the Integrated Documentation
This section provides reference information for various aspects of the Visual Basic language.
1. Typographic and Code Conventions.
Summarizes the way that keywords, placeholders, and other elements of the language are formatted in the
Visual Basic documentation.
3. Keywords
Lists all Visual Basic keywords and provides links to more information.
6. Data Types
Documents the data types available in Visual Basic.
7. Directives
Documents the compiler directives available in Visual Basic.
8. Functions
Documents the run-time functions available in Visual Basic.
9. Modifiers
Lists the Visual Basic run-time modifiers and provides links to more information.
10. Modules
Documents the modules available in Visual Basic and their members.
11. Nothing
Describes the default value of any data type.
12. Objects
Documents the objects available in Visual Basic and their members.
13. Operators
Documents the operators available in Visual Basic.
14. Properties
Documents the properties available in Visual Basic.
16. Statements
Documents the declaration and executable statements available in Visual Basic.
MSDN is a Microsoft program that provides developers with tools, information, training, and events to
help them develop products for Microsoft Windows platforms. MSDN Online, the Web site for developers
of Windows-based software, regularly features news, general information, and in-depth technical articles
and interviews.
Dialogs
A dialog box is a secondary window that allows users to perform a command, asks users a question, or
provides users with information or progress feedback.
Modal dialog boxes require users to complete and close before continuing with the owner window.
These dialog boxes are best used for critical or infrequent, one-off tasks that require completion before
continuing.
Modeless dialog boxes allow users to switch between the dialog box and the owner window as de-
sired. These dialog boxes are best used for frequent, repetitive, on-going tasks.
A task dialog is a dialog box implemented using the task dialog application programming interface
(API). They consist of the following parts, which can be assembled in a variety of combinations:
A title bar to identify the application or system feature where the dialog box came from.
A main instruction, with an optional icon, to identify the user's objective with the dialog.
A content area for descriptive information and controls.
A command area for commit buttons, including a Cancel button, and optional More options and Don't
show this again controls.
A footnote area for optional additional explanations and help, typically targeted at less experienced
users.
The Common Dialog control not an intrinsic control; rather, it is an "Active X" control that must be added
to the toolbox via the Components dialog box, as shown below. This dialog box is accessed via
the Project menu, Components item. Once you check "Microsoft Common Dialog Control 6.0" and
click OK, the control is added to your toolbox (also shown below, circled). Then you can double-click it
to make it appear on your form, as you would with any other control. The Common Dialog control is not
visible at run-time.
Me.ColorDialog1.ShowDialog()
Label1.ForeColor = Me.ColorDialog1.Color
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button2.Click
Me.Close()
End Sub
End Class
Press F5 to execute the program
The three screenshots below illustrate how different common dialog boxes are displayed..
“Change Color” button opens the ColorDialog box. You can choose any color from the palette and click
Ok. (The codes for event handling of Ok and Cancel button in the ColorDialogBox are not given in this
program. You may however write it as shown earlier, if you want to see the impact of your program.) The
next screenshot will show the changed fore color of the label1:
Now press F5 to execute the program. The Following sequence of three screenshot will illustrate the
working of the form:
The following screenshot shows the custom dialog box opened with the new text typed in the text box:
The final screenshot shows the changed label text as shown below:
Dialog.vb
Now, click on the Click Me button of the Windows Form, it displays the dialog box, as shown below.
Load Form1
Load frmTest
Unload Form1
Unload frmTest
The following are the most important list of properties related to a form. And these properties can be set
or read while the application is being executed.
Properties Description
BackColor It is used to set the background color for the form.
BackgroundImage It is used to set the background image of the form.
Cursor It is used to set the cursor image when it hovers over the form.
AllowDrop Using the AllowDrop control in a form, it allows whether to drag and drop on
the form.
Font It is used to get or set the font used in a form.
Locked It determines whether the form is locked or not.
FormBorderStyle It is used to set or get border style in a form.
Text It is used to set the title for a form window.
MinimizeBox MinimizeBox It is used to display the minimum option on the title bar of the
form.
IsMDIChild It is used to authenticate whether a form is a container of a Multiple Document
Interface (MDI) child form.
Autoscroll It allows whether to enable auto-scrolling in a form.
MaximizeBox It is used to display the maximum option on the title bar of the form.
MaximumSize It is used to set the maximum height and width of the form.
Language It is used to specifies the localized language in a form.
AcceptButton It is used to set the form button if the enter key is pressed.
Top, Left It is used to set the top-left corner coordinates of the form in pixel.
Name It is used to define the name of the form.
MinimumSize It is used to set the minimum height and width of the form.
Enabled It uses the True or False value to enable mouse or keyboard events in the form.
TopMost It uses a Boolean value that represents whether you want to put the window form
on top of the other form. By default, it is False.
For creating a Windows Forms application in VB.NET, we need to follow the following steps in
Microsoft Visual Studio.
1. GoTo File Menu.
2. Click on New Project.
3. Click on Windows Forms App or Application
And finally, click on the 'Create' button to create your project, and then, it displays the following window
form with a name Form1.
After filling all the details, click on the Submit button. After that, it shows the following Output:
2. Data Structures
Data structures allow programmers to streamline data collection when a large amount of related
information is involved. Let’s go back to our “visitorName” variable from above, but imagine the
computer programmer needs to store and reference 10 different visitors’ names rather than just one.
Rather than creating 10 different variables for each new visitor — which would increase the sheer
amount of text in the program and make adding or removing new contacts difficult — the programmer
could simply use a data structure to contain all related variables. In this case, the data structure would
be a List.
With this List data structure, the programmer only needs to create one variable rather than 10, which
means the code would be much more flexible to change.
3. Control Structures
A control structure analyzes variables and selects a direction in which to go determined from the given
parameters. For example, when a computer program is running, the code is being read by the computer
line by line from top to bottom and (for the most part) left to right.
As the code is being read, the computer will reach a point where it needs to make a “decision” (based
on strict rules set by the computer programmer). At this point, the code could do things like jump to a
different part of the program, re-run a certain piece of code again, or simply skip a block of code
altogether.
Whatever parameters are set by the programmer will affect the code flow. Think of control
structures as the directions your program needs to allow it to make choices and execute commands
under different conditions.
4. Syntax
Just like in the English language, computer programming follows a syntax or a set of rules that define
particular layouts of letters and symbols. Proper syntax ensures the computer reads and interprets code
accurately. For example, let’s consider a simple email address and its required syntax.
Email addresses are understood by readers and computers immediately due to their format. Typically,
email addresses must consist of a string of letters and numbers, followed by the “@” symbol, and
finally a website domain (e.g., [email protected]). This structure is known as the
standard email syntax! It’s easy to imagine that if the email address were not syntactically correct
([email protected]_smith), computers would not be able to process it.
In a similar fashion, each computer programming language has its own syntax or appropriate order in
how code should be written for the program to understand what it is supposed to do.
Code Editor
Use the Code window to write, display, and edit Visual Basic code. You can open as many Code windows
as you have modules, so you can easily view the code in different forms or modules, and copy and paste
between them.
You can open a Code window from:
The Project window, by selecting a form or module, and choosing the View Code button.
A UserForm window, by double-clicking a control or form, choosing Code from the View menu, or
pressing F7.
You can drag selected text to:
A different location in the current Code window.
Another Code window.
The Immediate and Watch windows.
The Recycle Bin.
Name the new module Math.vb and click the Add button. The new module will be added to the project
and a new tab labeled Math.vb for accessing the module code appears in the design area:
Now that we have added a new module to our project the next step is to add Visual Basic code to that
module. Before we can do that, however, we need to learn about Visual Basic procedures.
Visual Basic Code Procedures
Visual Basic procedures provide a way to break up code into logical and re-usable sections that can be
called from other sections of Visual Basic code. For example, you might have a section of Visual Basic
code that calculates the interest due on a loan.
Visual Basic provides two types of procedures:
functions - Functions are procedures which perform a task and return a value when completed.
subroutines - Subroutines are procedures which perform a task but return no value when completed.
Module Math
End Module
We are now going to add a subroutine called DisplayResult to this module. The syntax for a Visual Basic
subroutine is as follows:
scope Sub subroutineName(parameters)
End Sub
The scope value is either Private or Public depending on whether the Subroutine is to be accessible from
Visual Basic code outside of the current module. Sub is the Visual Basic keyword which indicates this is
a Subroutine rather than a Function. subroutineName is the name of the Subroutine and is used when this
specific procedure is to be called.
We can write code in the Subroutine to display a message window as follows:
Module Math
Public Sub DisplayResult()
MessageBox.Show("Test message")
End Sub
End Module
Next, the Click event procedure of the button in our form needs to call the DisplayResult() Subroutine.
Double click on the button in the form to display the event procedure code and add the call
to DisplayResult() as follows:
The final step, is to modify our Button control Click event procedure to call the PercentageOf() function,
passing through the Text properties of our two TextBox controls. The result returned by this function is
then passed to the DisplayResult() Subroutine where it is displayed in a message window:
After making the above change, press F5 to build and run the application.
Code window tips and comments
Applying block comments
Placing a single apostrophe in front of any line of code tells Excel to skip that line of code. This technique
is called commenting out code. Most programmers use the single apostrophe to create comments or notes
in the code, as shown here.
A single apostrophe in front of any line turns that line into a comment.
It’s sometimes beneficial to comment out multiple lines of code. This way, you can test certain lines of
code while telling Excel to ignore the commented lines.
You can copy entire blocks of code by highlighting the lines you need, and then holding down the Ctrl
key while dragging the block. This old Windows trick works even when you drag across modules.
You’ll know that you are dragging a copy when your cursor shows a plus symbol next to it, as shown
here.
This topic describes each category. Also, this topic describes how to combine multiple statements on a
single line and how to continue a statement over multiple lines.
Adding comments
Comment lines begin with an apostrophe (') or REM followed by a space. They can be added anywhere
in code, except within a string. To append a comment to a statement, insert an apostrophe or REM after
the statement, followed by the comment. Comments can also go on their own separate line. The following
example demonstrates these possibilities.
VBCopy
' This is a comment on a separate code line.
REM This is another comment on a separate code line.
x += a(i) * b(i) ' Add this amount to total.
MsgBox(statusMessage) REM Inform operator of status.
MANIPULATING DATA
Arithmetic expressions
Following table shows all the arithmetic operators supported by VB.Net. Assume variable A holds 2 and
variable B holds 7, then −
Operator Description Example
^ Raises one operand to the power of another B^A will give 49
+ Adds two operands A + B will give 9
- Subtracts second operand from the first A - B will give -5
* Multiplies both operands A * B will give 14
/ Divides one operand by another and returns a floating point result B / A will give 3.5
\ Divides one operand by another and returns an integer result B \ A will give 3
MOD Modulus Operator and remainder of after an integer division B MOD A will give 1
Example: Try the following example to understand all the arithmetic operators available in VB.Net −
Module operators
Sub Main()
Dim a As Integer = 21
Dim b As Integer = 10
Dim p As Integer = 2
Dim c As Integer
Dim d As Single
c=a+b
Console.WriteLine("Line 1 - Value of c is {0}", c)
c=a-b
Console.WriteLine("Line 2 - Value of c is {0}", c)
c=a*b
Console.WriteLine("Line 3 - Value of c is {0}", c)
d=a/b
Console.WriteLine("Line 4 - Value of d is {0}", d)
c=a\b
Console.WriteLine("Line 5 - Value of c is {0}", c)
c = a Mod b
Console.WriteLine("Line 6 - Value of c is {0}", c)
c=b^p
Console.WriteLine("Line 7 - Value of c is {0}", c)
Console.ReadLine()
End Sub End Module
VB Logical Operators
Following table shows all the logical operators supported by VB.Net. Assume variable A holds Boolean
value True and variable B holds Boolean value False, then −
Operator Description Example
And It is the logical as well as bitwise AND operator. If both the operands are (A And B) is
true, then condition becomes true. This operator does not perform short- False.
circuiting, i.e., it evaluates both the expressions.
Or It is the logical as well as bitwise OR operator. If any of the two operands (A Or B) is
is true, then condition becomes true. This operator does not perform short- True.
circuiting, i.e., it evaluates both the expressions.
Not It is the logical as well as bitwise NOT operator. Used to reverse the logical Not(A And
state of its operand. If a condition is true, then Logical NOT operator will B) is True.
make false.
Module logicalOp
Sub Main()
Dim a As Boolean = True
Dim b As Boolean = True
Dim c As Integer = 5
Dim d As Integer = 20
'logical And, Or and Xor Checking
If (a And b) Then
Console.WriteLine("Line 1 - Condition is true")
End If
If (a Or b) Then
Console.WriteLine("Line 2 - Condition is true")
End If
If (Not (a And b)) Then
Console.WriteLine("Line 10 - Condition is true")
End If
Console.ReadLine()
End Sub
End Module
VB Boolean Operators
A Boolean expression is an expression that evaluates to a value of the Boolean Data
Type: True or False. Boolean expressions can take several forms. The simplest is the direct comparison
of the value of a Boolean variable to a Boolean literal, as shown in the following example.
Dim A As Integer
Code language: VB.NET (vbnet)
to a Double, use the ToDouble method of the Convert class:
Dim B As Double
B = Convert.ToDouble(A)
Code language: VB.NET (vbnet)
Suppose that you have declared two integers, as follows:
Debug.Write(A / B)
Code language: VB.NET (vbnet)
displays the value 3.28571428571429. The result is a Double value, which provides the greatest possible
accuracy.
VB Array
An array stores a fixed-size sequential collection of elements of the same type. An array is used to store a
collection of data, but it is often more useful to think of an array as a collection of variables of the same
type.
For i = 0 To 10
n(i) = i + 100 ' set element at location i to i + 100
Next i
' output each array element's value '
For j = 0 To 10
Console.WriteLine("Element({0}) = {1}", j, n(j))
Next j
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Element(0) = 100
Element(1) = 101
Element(2) = 102
Element(3) = 103
Element(4) = 104
Element(5) = 105
Element(6) = 106
ALL RIGHTS RESERVED TO SVTI 36
Element(7) = 107
Element(8) = 108
Element(9) = 109
Element(10) = 110
Multi-Dimensional Arrays
VB.Net allows multidimensional arrays. Multidimensional arrays are also called rectangular arrays.
You can declare a 2-dimensional array of strings as −
Dim twoDStringArray(10, 20) As String
or, a 3-dimensional array of Integer variables −
Dim threeDIntArray(10, 10, 10) As Integer
The following program demonstrates creating and using a 2-dimensional array −
Module arrayApl
Sub Main()
' an array with 5 rows and 2 columns
Dim a(,) As Integer = {{0, 0}, {1, 2}, {2, 4}, {3, 6}, {4, 8}}
Dim i, j As Integer
' output each array element's value '
For i = 0 To 4
For j = 0 To 1
Console.WriteLine("a[{0},{1}] = {2}", i, j, a(i, j))
Next j
Next i
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
a[0,0]: 0
a[0,1]: 0
a[1,0]: 1
a[1,1]: 2
a[2,0]: 2
a[2,1]: 4
a[3,0]: 3
a[3,1]: 6
a[4,0]: 4
a[4,1]: 8
First example
A string literal is the notation for representing a string value within the text of a computer program. In
Visual Basic string literals are enclosed by double quotes. A string in Visual Basic is a sequence of
Unicode characters.
Option Strict On
Module Example
Sub Main()
Console.WriteLine(str1 + str2)
End Sub
End Module
In the preceding example, we create two string variables. Then we add them and compute the length of
the first string.
Dim str1 As String = "There are 10"
A string variable is declared and initiated.
Console.WriteLine(str1 + str2)
Two strings are concatenated. We use the + operator to add two strings.
Console.WriteLine("The length of the first string is " _
+ str1.Length.ToString() + " characters")
The Length property is used to determine the length of the string.
$ ./basics.exe
There are 10 apples
The length of the first string is 12 characters
Running the example gives this result.
Using quotes
Double quotes are used to create a string literal in Visual Basic. What if we wanted to display quotes, for
example in a direct speech? To print a double quote, it must be preceded by another double quote.
Option Strict On
Module Example
Sub Main()
Console.WriteLine("There are many stars.")
Console.WriteLine("He said, ""Which one is your favourite?""")
End Sub
End Module
When printing double quotes to the console, they must be preceded by another double quote.
Console.WriteLine("He said, ""Which one is your favourite?""")
Here we show, how to print a direct speech to the console. If we did not use two double quotes, the
compiler would be misled. It would see two consecutive strings.
$ ./quotes.exe
There are many stars.
He said, "Which one is your favourite?"
Output.
Multiline strings
It is possible to create a multiline string in Visual Basic.
Module Example
Sub Main()
Dim multiString As String = "I cheated myself" + vbNewLine + _
"like I knew I would" + vbNewLine + _
"I told ya, I was trouble" + vbNewLine + _
"you know that I'm no good"
Console.WriteLine(multiString)
End Sub
End Module
The example creates a string that spans several lines. We use a line continuation character, a plus operator
and a vbNewLine display constant.
$ ./multiline.exe
I cheated myself
like I knew I would
I told ya, I was trouble
you know that I'm no good
This text is displayed in four lines. All the text was assigned to one string variable.
Comparing strings
Option Strict On
Module Example
Sub Main()
Console.WriteLine("12" = "12") 'Returns True
Console.WriteLine("17" < "9") ' Returns True
Console.WriteLine("aa" > "ab") ' Returns False
End Sub
End Module
End Sub
End Module
There is an optional third ignoreCase argument that determines if the case should be honoured.
Console.WriteLine(String.Compare(str1, str2, True))
Compare two strings and ignore the case. This line prints 0 to the console.
There is a Like operator, which can be used for simple regular expression matching.
Option Strict On
Module Example
Dim words() As String = {"Seven", "even", "Maven", "Amen", "Leven"}
Sub Main()
For Each word As String In words
If word Like "?*even" Then
Console.WriteLine("{0} matches the pattern", word)
Else
Console.WriteLine("{0} does not match the pattern", word)
End If
Next
End Sub
End Module
Workarounds
To convert a Date literal to the format of your locale, or to a custom format, supply the literal to
the Format function, specifying either a predefined or user-defined date format. The following example
demonstrates this.
MsgBox("The formatted date is " & Format(#5/31/1993#, "dddd, d MMM yyyy"))
Alternatively, you can use one of the overloaded constructors of the DateTime structure to assemble a
date and time value. The following example creates a value to represent May 31, 1993 at 12:14 in the
afternoon.
Dim dateInMay As New System.DateTime(1993, 5, 31, 12, 14, 0)
A Variant is a special data type that can contain any kind of data except fixed-length String data.
(Variant types now support user-defined types.) A Variant can also contain the special
values Empty, Error, Nothing, and Null. You can determine how the data in a Variant is treated by using
the VarType function or TypeName function.
Use the VarType function to test what type of data is held in a Variant.
Numeric data can be any integer or real number value ranging from -1.797693134862315E308 to -
4.94066E-324 for negative values and from 4.94066E-324 to 1.797693134862315E308 for positive
values.
The Variant data type is the data type for all variables that are not explicitly declared as some other type
(using statements such as Dim, Private, Public, or Static).
A Variant is a special data type that can contain any kind of data except fixed-length String data.
(Variant types now support user-defined types.) A Variant can also contain the special
values Empty, Error, Nothing, and Null. You can determine how the data in a Variant is treated by using
the VarType function or TypeName function.
Use the VarType function to test what type of data is held in a Variant.
Numeric data can be any integer or real number value ranging from -1.797693134862315E308 to -
4.94066E-324 for negative values and from 4.94066E-324 to 1.797693134862315E308 for positive
values.
User-Defined Format
The syntax of the user-defined Format function is
Format (n, “user’s format”)
ALL RIGHTS RESERVED TO SVTI 42
Although it is known as user-defined format, we still need to follows certain formatting styles. Examples
of user-defined formatting style are listed in Table 19.2
Format Description Output
Format(781234.576,"0") Rounds to whole number without separators 781235
between thousands
Format(781234.576,"0.0") Rounds to 1 decimal place without separators 781234.6
between thousands
Format(781234.576,"0.00") Rounds to 2 decimal place without separators 781234.58
between thousands
Format(781234.576,"#,##0.00") Rounds to 2 decimal place with separators between 781,234.58
thousands
Format(781234.576,"$#,##0.00") Displays dollar sign and Rounds to 2 decimal place $781,234.58
with separators between thousands
Format(0.576,"0%") Converts to percentage form without decimal place 58%
Format(0.5768,"0%") Converts to percentage form with two decimal 57.68%
places
The Output
WRITING SUBROUTINES
Application Structure
A Visual Basic program is built up from standard building blocks. A solution comprises one or more
projects. A project in turn can contain one or more assemblies. Each assembly is compiled from one or
more source files. A source file provides the definition and implementation of classes, structures, modules,
and interfaces, which ultimately contain all your code.
Purpose of Subroutines
Subroutines make programs shorter as well as easier to read and understand, because they break program
code into smaller sections. You can test procedures or functions separately, rather than having to test the
whole program. This makes programs easier to debug.
There are a number of advantages to using subroutines to create ‘out of line’ blocks of code that can be
called by other parts of the program:
Subroutines make programs shorter as well as easier to read and understand, because they break
program code into smaller sections.
You can test procedures or functions separately, rather than having to test the whole program. This
makes programs easier to debug.
When creating very large programs, you can give different programmers different subroutines to
write, and these can then be combined.
If something needs to be changed in a subroutine, it only needs to be changed once, within the
subroutine code. This change will then take effect wherever in the program the subroutine is used.
You can use a subroutine many times in a program; if you wanted to repeat the same set of
instructions several times in a program without using a subroutine, you would have to write the
same code repeatedly.
Data that is passed to a subroutine can be customised, so a subroutine can perform the same action
on different data.
You can add subroutines to a library so that you can use them in other programs.
This example shows basic usage of procedures. In our program, we have two procedures.
The Main() procedure and the user defined SimpleProcedure(). As we already know,
the Main() procedure is the entry point of a Visual Basic program.
SimpleProcedure()
Each procedure has a name. Inside the Main() procedure, we call our user
defined SimpleProcedure() procedure.
Sub SimpleProcedure()
Console.WriteLine("Simple procedure")
End Sub
Procedures are defined outside the Main() procedure. Procedure name follows the Sub statement. When
we call a procedure inside the Visual Basic program, the control is given to that procedure. Statements
inside the block of the procedure are executed.
Functions
A function is a block of Visual Basic statements inside Function, End Function statements. Functions
return values.
There are two basic types of functions. Built-in functions and user defined ones. The built-in functions are
part of the Visual Basic language. There are various mathematical, string or conversion functions.
Option Strict On
Module Example
Sub Main()
Console.WriteLine(Math.Abs(-23))
Console.WriteLine(Math.Round(34.56))
Console.WriteLine("ZetCode has {0} characters", _
Len("ZetCode"))
End Sub
End Module
In the preceding example, we use two math functions and one string function. Built-in functions help
programmers do some common tasks.
In the following example, we have a user defined function.
Option Strict On
Two values are passed to the function. We add these two values and return the result to
the Main() function.
result = Addition(x, y)
Addition function is called. The function returns a result and this result is assigned to the result variable.
Function Addition(ByVal k As Integer, _
ByVal l As Integer) As Integer
Return k+l
End Function
This is the Addition function signature and its body. It also includes a return data type, for the returned
value. In our case is is an Integer. Values are returned to the caller with the Return keyword.
Arguments
When you call a Sub or Function procedure, you can supply arguments positionally, in the order that they
appear in the procedure's definition, or you can supply the arguments by name without regard to position.
For example, the following Sub procedure takes three arguments.
You can call this procedure by supplying its arguments in the correct position, each delimited by a comma,
as shown in the following example.
PassArgs "Mary", 29, #2-21-69#
You can also call this procedure by supplying named arguments, delimiting each with a comma.
PassArgs intAge:=29, dteBirth:=#2/21/69#, strName:="Mary"
A named argument consists of an argument name followed by a colon and an equal sign (:=), followed by
the argument value.
Named arguments are especially useful when you are calling a procedure that has optional arguments. If
you use named arguments, you don't have to include commas to denote missing positional arguments.
Using named arguments makes it easier to keep track of which arguments you passed and which you
omitted.
When you call a procedure with an optional argument, you can choose whether or not to specify the
optional argument. If you don't specify the optional argument, the default value, if any, is used. If no
default value is specified, the argument would be for any variable of the specified type.
The following procedure includes two optional arguments, the varRegion and varCountry variables.
The IsMissing function determines whether an optional Variant argument has been passed to the
procedure.
You can call this procedure by using named arguments as shown in the following example.
OptionalArgs varCountry:="USA", strState:="MD"
OptionalArgs strState:= "MD", varRegion:=5
ByRef in VB.NET means that a reference to the original value will be sent to the function (1). It's almost
like the original value is being directly used within the function. Operations like = will affect the original
value and be immediately visible in the calling function.
There are some more tests, but I want to keep this article straightforward and basic enough.
An Example Project
Because it is always easy to learn by doing things practically, you will be creating an app that makes use
of Regular Expressions to determine valid input.
Start Visual Studio and create a Desktop VB.NET application and design the form to resemble Figure.
Code
The Regular Expression's functionalities exist in the System.Text.RegularExpressions namespace, so let
us add that first:
Imports System.Text.RegularExpressions ' Regular Expressions Namespace
Add the following four variables inside the General Declarations section:
Private NameValid As Boolean 'Is Name Valid?
Private SurnameValid As Boolean 'Is Surname Valid?
Private PhoneValid As Boolean 'Is Phone Number Valid?
Private EmailValid As Boolean 'Is Email Valid?
These objects will determine if all our data is valid or not. Based on each of these variables' values, we
will know if the data is correct or not.
Step 4: Now validation should be triggered on Enter key press. Add following code to Enter key click
method.
Also make sure that Enter button's "CauseValidation" property should be set to "true".
Now our window form in ready with validation.
Creating a Menu
1. Click the MenuEditor component at the bottom of the screen. This will allow you to start entering
menu items. Type in Fileand press Enter.
2. You now have a File menu!
3. Click File, then underneath File where it displays text, as shown in Figure 1, type Open.
Repeat the steps to enter the Save, Recent, and Exit items to the File menu.
4. Add a menu item 'Edit' next to File and Add Cut, Copy, and Paste underneath it.
5. Add a Help menu with About, and Online items.
Now that you have the main menu sorted, let's take it a step further and add a submenu to the Open menu
item. To do this, follow these steps:
Once you click on the button, the Select Resource box will appear. Here, you can select from already
added icons inside your project, or add new items to your project's resources:
1. Click the Menu Item that you want to separate from other menu items.
2. When the 'Type Here' text appears, look closely. There is a small drop-down arrow next to it, as shown
in Figure.
3. Select Separator from the displayed list.
Your finished Menus should look like those shown in Figures 6-8.
In case this article isn't long enough already, I have added some basic code…
A toolbar is a classic control container. It can host text, buttons, etc. It is up to you to decide whether your
application needs a toolbar and what you want to position on it.
start a toolbar, declare a variable of this class. Because a toolbar is hosted by a container, namely a form,
if you want to display it, you should (must) add it to the Controls collection of its host. Here is an example:
Imports System.Windows.Forms
Controls.Add(tbrStandard)
End Sub
<STAThread()>
Public Shared Function Main() As Integer
Application.Run(New Exercise)
Return 0
End Function
End Class
This would produce:
Double-click the toolbar, which will cause the code window to open with the ButtonClick event for the
toolbar, which is the event we want to code for. The Sub procedure header looks like this:
Run the program. When you click on a toolbar button ("Print" for example), the corresponding menu
procedure code should execute:
Creating a StatusBar
tatusBar class represents a StatusBar.
Dim mainStatusBar As New StatusBar()
A StatusBar is a combination of StatusBar panels. StatusBarPanel class represents a StatusBar panel. The
following code snippet creates two panels and adds them to the StatusBar.
ALL RIGHTS RESERVED TO SVTI 56
Dim statusPanel As New StatusBarPanel()
Dim datetimePanel As New StatusBarPanel()
statusPanel.BorderStyle = StatusBarPanelBorderStyle.Sunken
statusPanel.Text = "Application started. No action yet."
statusPanel.ToolTipText = "Last Activity"
statusPanel.AutoSize = StatusBarPanelAutoSize.Spring
mainStatusBar.Panels.Add(statusPanel)
datetimePanel.BorderStyle = StatusBarPanelBorderStyle.Raised
datetimePanel.ToolTipText = "DateTime: " + System.DateTime.Today.ToString()
datetimePanel.Text = System.DateTime.Today.ToLongDateString()
datetimePanel.AutoSize = StatusBarPanelAutoSize.Contents
mainStatusBar.Panels.Add(datetimePanel)
Controls.Add(mainStatusBar)
Now let's create a Windows Forms application with a few controls on it. We are going to show current
activity and date on the status bar. The Form looks like following.
Here bottom of window show the status of Checkbox and show current date.
Some Common Controls in VB.NET Control
VB.NET has a variety of controls, below given are the list of commonly used controls.
Text Box
As you can guess, it is used to accept textual input from the user. The user can add strings, numerical
values and a combination of those, but Images and other multimedia content are not supported.
Example:
Label
It is used to show any text to the user, typically the text in a label does not change while the application is
running.
Button
It is used as a standard Windows Button. In most cases, the Button Control is used to generate a click
event, its name, size and appearance are not changed in the runtime.
Example:
Public Class Form1
Private Sub ButtonExmaple_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Text = "educba.com"
End Sub
Private Sub quitBTN _Click(sender As Object, e As EventArgs) Handles quitBTN.Click
Application.Exit()
End Sub
End Class
List Box
As the name suggests, this control works as a way to display a list of items on the application. Users can
select any options from the list.
Example:
Public Class example
Private Sub dropexmaple_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ListBox1.Items.Add("India")
ListBox1.Items.Add("Pakistan")
ListBox1.Items.Add("USA")
End Sub
Private Sub BTN1_Click(sender As Object, e As EventArgs) Handles BTN1.Click
MsgBox("The country you have selected is " + ListBox1.SelectedItem.ToString())
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs)
Handles ListBox1.SelectedIndexChanged
Textlable2.Text = ListBox1.SelectedItem.ToString()
End Sub
End Class
Radio Button
Radio Button is one of the popular ways of limiting the user to pick just one option. The programmer can
set any of the buttons as default if needed. These buttons are grouped together.
Example:
Public Class example
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Private Sub Example_RadioButton1_CheckedChanged(sender As Object, _
e As EventArgs) Handles RadioButton1.CheckedChanged
Me.BackColor = Color.Black
End Sub
Private Sub Example_RadioButton2_CheckedChanged(sender As Object, _
e As EventArgs) Handles RadioButton2.CheckedChanged
Me.BackColor = Color.White
End Sub
Private Sub Example_RadioButton3_CheckedChanged(sender As Object, _
e As EventArgs) Handles RadioButton3.CheckedChanged
Me.BackColor = Color.Brown
End Sub
End Class
Checkbox
Checkboxes are similar to radio buttons in the way that they are also used in groups, however, a user can
select more than one item in the group.
Example:
Public Class Form1
Private Sub Submit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
Dim msg As String = ""
If ExampleCheckBox1.Checked = True Then
msg = " ExampleCheckBox1 Selected"
End If
If ExampleCheckBox2.Checked = True Then
msg = msg & " ExampleCheckBox2 Selected "
End If
Picture Box
This VB.Net control is used to show images and graphics inside a form. The image can be of any supported
format and we can select the size of the object in the form too.
Example:
Scroll Bar
When the content in the form is too large to be shown at once, we can use ScrollBars to let users scroll to
see the remaining content, it can be vertical, horizontal or even both depending on the circumstances.
Example:
VB.NET Arrays
An array is a linear data structure that is a collection of data elements of the same type stored on
a contiguous memory location. Each data item is called an element of the array. It is a fixed size of
In the above diagram, we store the Integer type data elements in an array starting at index 0. It will continue
to store data elements up to a defined number of elements.
Declaration of VB.NET Array
We can declare an array by specifying the data of the elements followed by parentheses () in the VB.NET.
1. Dim array_name As [Data_Type] ()
In the above declaration, array_name is the name of an array, and the Data_Type represents the
type of element (Integer, char, String, Decimal) that will to store contiguous data elements in the
VB.NET array.
Now, let us see the example to declare an array.
2. 'Store only Integer values
3. Dim num As Integer() or Dim num(5) As Integer
4. 'Store only String values
5. Dim name As String() or Dim name(5) As String
6. ' Store only Double values
7. Dim marks As Double()
Furthermore, we can also initialize and declare an array using the following ways, as shown below.
1. Dim intData() As Integer = {1, 2, 3, 4, 5}
2. Dim intData(5) As Integer
3. Dim array_name() As String = {"Peter", "John", "Brock", "James", "Maria"}
4. Dim misc() as Object = {"Hello friends", 16c, 12ui, "A"c}
5. Dim Emp(0 to 2) As String
6. Emp{0} = "Mathew"
7. Emp(1) = " Anthony"
8. Emp(2) = "Prince"
Output:
The data residing in a data store or database is retrieved through the data provider. Various components
of the data provider retrieve data for the application and update data.
An application accesses data either through a dataset or a data reader.
Datasets store data in a disconnected cache and the application retrieves data from it.
Data readers provide data to the application in a read-only and forward-only mode.
Data Provider
A data provider is used for connecting to a database, executing commands and retrieving data, storing it
in a dataset, reading the retrieved data and updating the database.
DataSet
DataSet is an in-memory representation of data. It is a disconnected, cached set of records that are
retrieved from a database. When a connection is established with the database, the data adapter creates a
dataset and stores data in it. After the data is retrieved and stored in a dataset, the connection with the
database is closed. This is called the 'disconnected architecture'. The dataset works as a virtual database
containing tables, rows, and columns.
The DataSet class is present in the System.Data namespace. The following table describes all the
components of DataSet –
1 DataTableCollection
It contains all the tables retrieved from the data source.
2 DataRelationCollection
It contains relationships and the links between tables in a data set.
3 ExtendedProperties
It contains additional information, like the SQL statement for retrieving data, time of
retrieval, etc.
4 DataTable
It represents a table in the DataTableCollection of a dataset. It consists of the DataRow and
DataColumn objects. The DataTable objects are case-sensitive.
5 DataRelation
It represents a relationship in the DataRelationshipCollection of the dataset. It is used to
relate two DataTable objects to each other through the DataColumn objects.
6 DataRowCollection
It contains all the rows in a DataTable.
7 DataView
It represents a fixed customized view of a DataTable for sorting, filtering, searching, editing
and navigation.
8 PrimaryKey
It represents the column that uniquely identifies a row in a DataTable.
9 DataRow
It represents a row in the DataTable. The DataRow object and its properties and methods
are used to retrieve, evaluate, insert, delete, and update values in the DataTable. The
NewRow method is used to create a new row and the Add method adds a row to the table.
10 DataColumnCollection
It represents all the columns in a DataTable.
11 DataColumn
It consists of the number of columns that comprise a DataTable.
Connecting to a Database
The .Net Framework provides two types of Connection classes −
SqlConnection − designed for connecting to Microsoft SQL Server.
OleDbConnection − designed for connecting to a wide range of databases, like Microsoft Access and
Oracle.
Example 1
We have a table stored in Microsoft SQL Server, named Customers, in a database named testDB. Please
consult 'SQL Server' tutorial for creating databases and database tables in SQL Server.
Select a server name and the database name in the Add Connection dialog box.
Choose the database object, Customers table in our example, and click the Finish button.
When the application is run using Start button available at the Microsoft Visual Studio tool bar, it will
show the following window −
Example 2
In this example, let us access data in a DataGridView control using code. Take the following steps −
Me.CUSTOMERSTableAdapter.Fill(Me.TestDBDataSet.CUSTOMERS)
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
End Sub
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool
bar, it will show the following window −
Clicking the Fill button displays the table on the data grid view control −
Example 3
So far, we have used tables and databases already existing in our computer. In this example, we will create
a table, add columns, rows and data into it and display the table using a DataGridView object.
Take the following steps −
Add a DataGridView control and a button in the form.
Change the text of the button control to 'Fill'.
Add the following code in the code editor.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
End Sub
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool
bar, it will show the following window −
Clicking the Fill button displays the table on the data grid view control −
The following figure is a graphical representation of the various stages of a typical SDLC.
In the Create a new project window, choose Visual Basic from the Language list. Next,
choose Windows from the Platform list and Console from the project types list.
After you apply the language, platform, and project type filters, choose the Console Application template,
and then choose Next.
Then, in the Visual Studio Installer, choose the .NET Core cross-platform development workload. After
that, choose the Modify button in the Visual Studio Installer. You might be prompted to save your work;
if so, do so. Next, choose Continue to install the workload. Then, return to step 2 in this "Create a project"
procedure.
In the Configure your new project window, type or enter WhatIsYourName in the Project name box.
Then, choose Next.
Let's create an app that prompts you for your name and then displays it along with the date and time.
Here's how:
1. In the WhatIsYourName project, enter the following Visual Basic code immediately after the opening
bracket that follows the Sub Main(args As String()) line and before the End Sub line:
VBCopy
Console.WriteLine(vbCrLf + "What is your name? ")
Dim name = Console.ReadLine()
Dim currentDate = DateTime.Now
Console.WriteLine($"{vbCrLf}Hello, {name}, on {currentDate:d} at {currentDate:t}!")
Console.Write(vbCrLf + "Press any key to exit... ")
Console.ReadKey(True)
This code replaces the existing WriteLine, Write, and ReadKey statements.
Deploying VB Applications
First of all, load your application in Visual Basic 2017. In this example, I wish to publish my Draw Text
application. In the VB2017 IDE, choose Build and then select Publish Draw text, as shown in the
following figure.
Click the Next button to continue. Now, the Publish Wizard will ask you how will users install the
application. There are three options, from a website, from a UNC path or file share and from a CD-ROM
or DVD-ROM. In this example, we choose CD-ROM or DVD-ROM, as shown in the following figure:
You may click the Next button to continue with the Publish Wizard or the Finish button to complete the
publishing process. If you click the Next button, the Publish Wizard will ask where will the application
After clicking the Next button, the final screen of the Publish Wizard will show you where the application
will be published to.
Upon clicking the Finish button, the installation files and folder will be saved to the specified location. In
our examples, the folder is Application files and the files are Draw text.application and setup.exe. You
may now burn the folder and files into a CD-ROM, DVD-ROM or upload them to a website for
distribution to the users.
1. logic tier,
2. the presentation tier, and
3. the data tier.
The following are the most important list of events related to a form.
Events Description
Activated An activated event is found when the user or program activates the form.
Click A click event is active when the form is clicked.
Closed A closed event is found before closing the form.
Closing It exists when a form is closing.
DoubleClick DoubleClick
The DoubleClick event is activated when a user double clicks on the form.
DragDrop A DragDrop event is activated when a drag and drop operation is performed.
MouseDown A MouseDown event is activated when the mouse pointer is on the form, and the
mouse button is pressed.
GotFocus A GotFocus event is activated when the form control receives a focus.
HelpButtonClicked It is activated when a user clicked on the help button.
KeyDown A KeyDown event is activated when a key is pressed while focussing on the
form.
KeyUp A KeyUp event is activated when a key is released while focusing on the form.
Load The load event is used to load a form before it is first displayed.
LostFocus It is activated when the form loses focus.
MouseEnter A MouseEnter event is activated when the mouse pointer enters the form.
MouseHover A MouseHover event is activated when the mouse pointer put on the form.
MouseLeave A MouseLeave event is activated when the mouse pointer leaves the form
surface.
Shown It is activated whenever the form is displayed for the first time.
Scroll A Scroll event is activated when a form is scrolled through a user or code.
Resize A Resize event is activated when a form is resized.
Move A Move event is activated when a form is moved.
And finally, click on the 'Create' button to create your project, and then, it displays the following window
form with a name Form1.
After filling all the details, click on the Submit button. After that, it shows the following Output:
DIALOG LAYOUT
Laying Out a Dialog Interface
All controls within a utility dialog should start at the top/left and flow downward.
Never center controls on a dialog to fill a large area.
Use the environment font for all dialog text. When writing a visual spec, specify the environment font
instead of selecting a particular font and size. See The environment font.
Use consistent control spacing and placement to support the goal for quality in craftsmanship.
Dialogs can become more complex from a larger number of controls, a unique juxtaposition of
controls, or both. For those complex situations, allow adequate space between control groupings to
give the user a logical flow to parse.
Both controls are populated and customized in the very same way. At design time, when a control is
focused, a navigation toolbar contains buttons to add a new page or remove the currently active page (see
below). Arrow buttons allow users to navigate through pages. The index of the currently displayed page
is shown on the toolbar’s left side.
1. Color Dialog Box: It is used to display the color dialog box that allows the user to select a color from
the predefined colors or specify the custom colors.
2. Font DialogBox: It is used to create a Font dialog box that allows the user to select the font, font size,
color, and style to be applied to the current text selection.
3. OpenFile Dialog Box: It is used to create a prompt box that allows the users to select a file to open
and allows the selection of multiple files.
4. Print Dialog Box: It is used to create a print dialog box that allows the user to print documents by
selecting the printer and setting of the page printed through the Windows application.
Dialog.vb
Now, click on the Click Me button show you validation for confirmation , it displays the dialog box, as
shown below.
DATA DECLARATIONS
Scope in Visual Basic Programs
Scope, in programming terms, refers to the visibility of assets. These assets include variables, arrays,
functions, classes, and structures. Visibility in this case means which parts of your program can see or use
it.
Essentially, there are four levels of scope in Visual Basic. These are:
Block scope: Available only within the code block in which it is declared
Procedure scope: Available to all code within the procedure in which it is declared
Module scope: Available to all code within the module, class, or structure in which it is declared
Namespace scope: Available to all code in the namespace in which it is declared
Block Scope
A block is a set of statements enclosed within starting and ending declaration statements, such as the
following:
If and End If
Select and End Select
Do and Loop
While and End While
For [Each] and Next
Try and End Try
With and End With
If you declare a variable within a block, such as the above-mentioned examples, you can use it only within
that block. In the following example, the scope of the SubTotal variable is the block between the If and
End If statements. Because the variable SubTotal has been declared inside the block, you cannot refer to
SubTotal when execution passes out of the block.
1. If Tax > 15.0 Then
2. Dim SubTotal As Decimal
3. SubTotal = Tax * SubTotal 'Correct'
4. End If
5. 'Wrong. Will Not Work Because SubTotal is Out of Scope!'
6. MessageBox.Show(SubTotal.ToString())
Procedure Scope
Procedure scope refers to an an element that is declared within a procedure is not available outside that
procedure. Only the procedure that contains the declaration can use it. Variables at this level are usually
known as local variables.
In the following example, the variable strWelcome declared in the ShowWelcome Sub procedure cannot
be accessed in the Main Sub procedure:
1. Sub Main()
2. ShowWelcome()
3. Console.WriteLine(strWelcome) 'Will not work!'
4. Console.WriteLine("Press Enter to continue...")
5. Console.ReadLine()
6. End Sub
7. Sub ShowWelcome()]
8. Dim strWelcome = "Hello friend"
Module Scope
You can declare elements at the Module level by placing the declaration statement outside of any
procedure or block but within the module, class, or structure. When you create a variable at module level,
the access level you choose determines the scope. More on Access Modifiers later.
Private elements are available to every procedure in that particular module, but not to any code in a
different module.
In the following example, all procedures defined in the module can refer to the string variable strWelcome.
When the second procedure is called, it displays the contents of the string variable strWelcome in a
messagebox.
1. Private strWelcome As String 'Outside of all Procedures'
2. Sub StoreWelcomeGreeting()
3. strWelcome = "Welcome to the world of Programming"
4. End Sub
5.
6. Sub SayWelcome()
7. MessageBox.Show(strWelcome)
8. End Sub
Namespace Scope
Namespace scope can be thought of as project scope. By declaring an element at module level using either
the Friend or Public keyword, it becomes available to all procedures throughout the namespace in which
the element is declared. An element available from within a certain namespace also is available from
within any namespaces that are nested inside that namespace. Public elements in a class, module, or
structure are available to any project that references their project, as well.
If I had changed the declaration of strWelcome (from the previous example) to:
What is a Variable?
A variable is a simple name used to store the value of a specific data type in computer memory.
In VB.NET, each variable has a particular data type that determines the size, range, and fixed space in
computer memory. With the help of variable, we can perform several operations and manipulate data
values in any programming language.
VB.NET Variables Declaration
The declaration of a variable is simple that requires a variable name and data type followed by a Dim. A
Dim is used in Class, Module, structure, Sub, procedure.
Syntax:
1. Dim [Variable_Name] As [Defined Data Type]
There are some valid declarations of variables along with their data type definition, as shown below:
1. Dim Roll_no As Integer
2. Dim Emp_name As String
3. Dim Salary As Double
4. Dim Emp_id, Stud_id As Integer
5. Dim result_status As Boolean
Further, if we want to declare more than one variable in the same line, we must separate each variable
with a comma.
Syntax
1. Dim Variable_name1 As DataType1, variable_name2 As DataType2, Varia-
ble_name3 As DataType3
Note: The statements given below is also used to declare the variable with their data type:
1. Static name As String
2. Public bill As Decimal = 0
Let's create a program to use different types of variable declaration and initialization in VB.NET.
Variable1.vb
1. Imports System
2. Module Variable1
3. Sub Main()
4. 'declaration of intData as Integer
5. Dim intData As Integer
6. 'declaration of charData as Char
7. Dim CharData As Char
8. 'declaration of strData as String
9. Dim strData As String
10. 'declaration of dblData as Double
11. Dim dblData As Double
12. 'declaration of single_data as Single
13. Dim single_data As Single
14. 'Initialization of intData
15. intData = 10
16. 'Initialization of CharData
17. CharData = "A"
18. 'Initialization of strData
19. strData = " VB.NET is a Programming Language."
20. dblData = 4567.676
21. 'Initialization of dblData
22. 'Initialization of single_data
23. single_data = 23.08
24. Console.WriteLine(" Value of intData is: {0}", intData)
25. Console.WriteLine(" Value of CharData is: {0}", CharData)
26. Console.WriteLine(" Value of strData is: {0}", strData)
27. Console.WriteLine(" Value of dblData is: {0}", dblData)
28. Console.WriteLine(" Value of single_data is: {0}", single_data)
29. Console.WriteLine("press any key to exit...")
30. Console.ReadKey()
31. End Sub
32. End Module
Output:
Value of intData is: 10
Value of CharData is: A
Value of strData is: VB.NET is a Programming Language.
Value of dblData is: 4567.676
Value of single_data is: 23.08
press any key to exit...
Try the following example to understand all the logical/bitwise operators available in VB.Net −
Module logicalOp
Sub Main()
Dim a As Boolean = True
Dim b As Boolean = True
Dim c As Integer = 5
Dim d As Integer = 20
'logical And, Or and Xor Checking
If (a And b) Then
Console.WriteLine("Line 1 - Condition is true")
End If
If (a Or b) Then
Console.WriteLine("Line 2 - Condition is true")
End If
If (a Xor b) Then
Console.WriteLine("Line 3 - Condition is true")
End If
'bitwise And, Or and Xor Checking
If (c And d) Then
VB.Net provides following types of loops to handle looping requirements. Click the following links to
check their details.
Loop Type Description
Do Loop It repeats the enclosed block of statements while a Boolean condition is True or until
the condition becomes True. It could be terminated at any time with the Exit Do
statement.
For...Next It repeats a group of statements a specified number of times and a loop index counts
the number of loop iterations as the loop executes.
For Each...Next It repeats a group of statements for each element in a collection. This loop is used for
accessing and manipulating all elements in an array or a VB.Net collection.
While... End It executes a series of statements as long as a given condition is True.
While
With... End It is not exactly a looping construct. It executes a series of statements that repeatedly
With refer to a single object or structure.
Nested loops You can use one or more loops inside any another While, For or Do loop.
Exit statement Terminates the loop or select case statement and transfers execution to
the statement immediately following the loop or select case.
Continue statement Causes the loop to skip the remainder of its body and immediately retest
its condition prior to reiterating.
GoTo statement Transfers control to the labeled statement. Though it is not advised to
use GoTo statement in your program.
Do-While Example
For-Each Example
Debugging application
Syntax Errors
Syntax errors are those that appear while you write code. If you're using Visual Studio, Visual Basic
checks your code as you type it in the Code Editor window and alerts you if you make a mistake, such as
misspelling a word or using a language element improperly. If you compile from the command line, Visual
Basic displays a compiler error with information about the syntax error. Syntax errors are the most
common type of errors. You can fix them easily in the coding environment as soon as they occur.
Run-Time Errors
Run-time errors are those that appear only after you compile and run your code. These involve code that
may appear to be correct in that it has no syntax errors, but that will not execute. For example, you might
correctly write a line of code to open a file. But if most the file does not exist, the application cannot open
the file, and it throws an exception. You can fix run-time errors by rewriting the faulty code or by
using exception handling, and then recompiling and rerunning it.
Logic Errors
Logic errors are those that appear once the application is in use. They are most often faulty assumptions
made by the developer, or unwanted or unexpected results in response to user actions. For example, a
mistyped key might provide incorrect information to a method, or you may assume that a valid value is
always supplied to a method when that is not the case. Although logic errors can be handled by
using exception handling (for example, by testing whether an argument is Nothing and throwing
an ArgumentNullException), most commonly they should be addressed by correcting the error in logic
and recompiling the application.
APPLICATION FRAMEWORKS
SDI and MDI Applications
SDI applications allow only one open document frame window at a time. MDI applications allow multiple
document frame windows to be open in the same instance of an application.
An MDI application has a window within which multiple MDI child windows, which are frame windows
themselves, can be opened, each containing a separate document. In some applications, the child windows
can be of different types, such as chart windows and spreadsheet windows. In that case, the menu bar can
change as MDI child windows of different types are activated.
The tables below show the various objects, properties, and methods available with the FSO.
Object Description
FileSystemObject The FSO itself, highest level of the FSO object model. Allows the
programmer to interact with Files, Folders and Drives. The programmer
can use the FSO objects to create directories, move files, determine whether
or not a Drive exists, etc.
Drive The Drive object is used to examine information on disk, CD-ROM, RAM
disk, and network drives; the Drives collection provides a list of physical
and logical drives on the system.
File object The File object is used to examine and manipulate files;
the Files collection provides a list of files in a folder.
Folder object The Folder object is used to examine and manipulate folders;
the Folders collection provides a list of subfolders in a folder.
TextStream object Used to read and write text files.
The Registry
When programming in Visual Basic, you can choose to access the registry by means of either the functions
provided by Visual Basic or the registry classes of .NET. The registry hosts information from the operating
system as well as information from applications hosted on the machine. Working with the registry may
compromise security by allowing inappropriate access to system resources or protected information.
In This Section
How to: Create a Registry Key and Set Its Value:
Describes how to use the CreateSubKey and SetValue methods of the My.Computer.Registry object to
create a registry key and set its value.
Reading from and Writing to the Registry Using the Microsoft.Win32 Namespace:
Describes how to use the Registry and RegistryKey classes of .NET to access the registry.
Security and the Registry: Discusses security issues involving the registry.
DEPLOYING APPLICATIONS
The Packaging and Deployment Wizard
Visual Studio .NET provides you the ability to deploy your applications easily. If you click File->Add
Project->New Project, that brings up the template dialog in which you can create a deployment project.
As you can see in Figure, you can choose from a few different types of deployment options.
Cabinet Files
Cabinet files (or .cab files) are compressed files of your existing files. A few restrictions apply to using
.cab files. First of all, your .cab file can contain only one assembly, so a .cab is good if you are distributing
a single DLL component or single executable program. Also a .cab file must have the same name as the
assembly it is packaging. For example, our SmileyFace.dll cabinet file would have to be named
SmileyFace.cab.
Merge Modules
Merge modules (or .msm files) are used in conjunction with .msi files to install components. The merge
module contains all of the file and registry information needed to install your component and can be shared
with different .msi files that also need to install the component. Merge modules are useful because they
Setup Project
The setup project allows you to create an .msi file that will install all the necessary files onto a system for
running your application. Once you've created your project, you'll need to add files to the project. If you
right-click on the setup project and choose Add->File, you can add the files you need to deploy. See Figure
26.6.
You also need to bring up the Configuration Manager (under Build->Configuration Manager) to tell it to
compile your setup project by checking the Build button.
Once you have added the files you want to deploy (executable files and other assemblies, graphics files,
readme files, Help files, even source code if you wish), choose Build Solution from the Build menu.
This will create up to five files: Setup.exe, Setup2.msi, setup.ini, InstMsiA.exe, and InstMsiW.exe.
These files are everything you need to deploy your application on another system. The files include the
distributable runtime and all other dependencies. In other words, we can take the files created by the
deployment build, burn them on a CD, bring them to a computer that doesn't have the .NET Framework
installed, and run setup.exe to install the application with all the necessary files.
The next screen allows us to include outputs from existing projects. This includes primary output such
as the executable file or the component, documentation, source code, debug information files, Help files,
localized assemblies, and even other setup files referenced in this project.
Finally, we need to choose any additional miscellaneous files we are interested in for this project such as
a readme file, graphic and sound files, or HTML files. Don't worry if you forget to add files here,
because you can always add them later in the Solution Explorer by rightclicking on the setup project and
choosing Add->File.
Setup will install the project into the directory c:\program files\<name of your company>\SetupName\.
To place the program in the Start menu, first bring up the File System view by double-clicking a project
output in the setup project in the Solution Explorer.
Now we need to add a shortcut to the application inside the folder. Right-click in the right-hand pane
and choose Create New Shortcut.
This brings up the Select Item in Project dialog. Click all the way down into the project folder you just
created.
Double-click the Application folder to find the shortcut for the application.
Look for the application you want to install a shortcut for and click on the Add File button.
Finding the File for the Shortcut
In most cases you want to add to the Program menu the application's executable file as well as a readme
file or any Help files and documentation associated with the application. After the deployment project has
been compiled and setup has been run, the application will appear in the Programs menu as shown in
Figure.
What is Database?
A database is an organized collection of information, which can be used alone, or combined / related to
other data for multiple purposes. Database is made up of files, records and field.
For example: if we have data about marks obtained by all students, we can then conclude about toppers
and average marks.
Database Management System
A database management system (DBMS) is software of collection of small programs that enables to store,
modify, and extract information from a database.
DBMS examples include MySQL, Microsoft Access,SQL Server, FileMaker, Oracle, RDBMS.
The database management system (DBMS), on the other hand is the software or tool that is used to
manage the database and its users.
A DBMS consist of different components or subsystems.
Each subsystem or component of the DBMS performs different function(s), so a DBMS is collection
of different programs but they all work jointly to manage the data stored in the database and its users.
Sometimes another term is used, that is, the DATABASE SYSTEM , again, this term has been used
differently by different people, however in this subject we use the term database system as a
combination of database and the database management system.
So database is collection of data, DBMS is tool to manage this data, and both jointly are called
DATABASE SYSTEM.
Introduction to relational database
A relational database is a collection of information that organizes data points with defined relationships
for easy access. In the relational database model, the data structures -- including data tables, indexes and
views -- remain separate from the physical storage structures, enabling database administrators to . the
physical data storage without affecting the logical data structure.
A user can get a database report showing the data they need. For example, a branch office manager might
want a report on all customers that bought products after a certain date. A financial services manager in
the same company could, from the same tables, obtain a report on accounts that need to be paid.
When creating a relational database, users define the domain of possible values in a data column and
constraints that may apply to that data value. For example, a domain of possible customers could allow
up to 10 possible customer names, but it is limited in one table to allowing only three of these customer
names to be specifiable.
Two constraints relate to data integrity and the primary and foreign keys:
Entity integrity ensures that the primary key in a table is unique and the value is not set to null.
Referential integrity requires that every value in a foreign key column will be found in the primary
key of the table from which it originated.
Logical data independence is a system's ability to manage the conceptual schema without altering the
external schema or application programs. Conceptual schema alterations may include the addition or
deletion of new relationships, entities or attributes without altering existing external schemas or rewriting
application programs.
Types of databases
There are several database categories, from basic flat files that aren't relational to NoSQL and
newer graph databases that are considered even more relational than standard relational databases. Some
database types include the following:
Flat file database. These databases consist of a single table of data that has no interrelation -- typically text
files. This type of file enables users to specify data attributes, such as columns and data types.
Find out about the advantages and disadvantages of flat file and relational databases.
NoSQL database. This type of database is an alternative that's especially useful for large, distributed data
sets. NoSQL databases support a variety of data models, including key-value, document, columnar and
graph formats.
Graph database. Expanding beyond traditional column- and row-based relational data models; this
NoSQL database uses nodes and edges that represent connections between data relationships and can
discover new relationships between the data. Graph databases are more sophisticated than relational
databases. They are used for fraud detection or web recommendation engines.
However, an ORD can also be considered object storage, particularly for software written in the object-
oriented programming language, thus pulling on object-oriented characteristics. In this situation, APIs are
used in the storage and retrieval of data.
Categorizing data. Database administrators can easily categorize and store data in a relational
database that can then be queried and filtered to extract information for reports. Relational databases
are also easy to extend and aren't reliant on physical organization. After the original database creation,
a new data category can be added without having to modify the existing applications.
Accuracy. Data is stored just once, eliminating data deduplication in storage procedures.
Ease of use. Complex queries are easy for users to carry out with SQL, the main query language used
with relational databases.
Security. Direct access to data in tables within an RDBMS can be limited to specific users.
Structure. Relational databases require a lot of structure and a certain level of planning because
columns must be defined and data needs to fit correctly into somewhat rigid categories. The structure
is good in some situations, but it creates issues related to the other drawbacks, such as maintenance
and lack of flexibility and scalability.
Maintenance issues. Developers and other personnel responsible for the database must spend time
managing and optimizing the database as data gets added to it.
Inflexibility. Relational databases are not ideal for handling large quantities of unstructured data. Data
that is largely qualitative, not easily defined or dynamic is not optimal for relational databases, because
as the data changes or evolves, the schema must evolve with it, which takes time.
Lack of scalability. Relational databases do not horizontally scale well across physical storage
structures with multiple servers. It is difficult to handle relational databases across multiple servers
because as a data set gets larger and more distributed, the structure is disrupted, and the use of multiple
servers has effects on performance -- such as application response times -- and availability.
What are the differences between relational databases, non-relational databases and NoSQL?
The most important difference between relational database systems and non-relational database systems
is that relational databases are normalized. That is, they store data in a tabular form, arranged in a table
with rows and columns. A non-relational database stores data as files.
ALL RIGHTS RESERVED TO SVTI 112
Other differences include the following:
Use of primary keys. Relational database tables each have a primary key identifier. In a non-relational
database, data is normally stored in hierarchical or navigational form, without the use of primary keys.
Data values relationships. Since data in a relational database is stored in tables, the relationship
between these data values is stored as well. Since a non-relational database stores data as files, there
is no relationship between the data values.
Integrity constraints. In a relational database, the integrity constraints are any constraint that ensures
database integrity. They are defined for the purpose of atomicity, consistency, isolation and durability,
or ACID. Non-relational databases do not use integrity constraints.
Structured vs. unstructured data. Relational databases work well for structured data that conforms
to a predefined data model and doesn't change much. Non-relational databases are better for
unstructured data, which doesn't conform to a predefined data model and can't be stored in an RDBMS.
Examples of unstructured data include text, emails, photos, videos and web pages.
Non-relational databases are also called NoSQL databases. The terms are used interchangeably, but there
are differences.
SQL is the query language that is used with relational databases. Relational databases and their
management systems almost always use SQL as their underlying query language. NoSQL, or not only
SQL, databases use SQL and other query languages. For example, the NoSQL database management
program MongoDB uses JSON-like documents to store and organize data. (Technically, it uses a variant
of JSON call BSON, or binary JSON.)
Referring to databases as non-relational vs. relational categorizes them based on their architecture, and
referring to them as SQL vs. NoSQL categorizes them based on the query language, whether it is solely
SQL or not only SQL. Often, a relational database can be referred to as a SQL database, as many of them
use SQL, and non-relational databases can be referred to as NoSQL databases. NoSQL and non-relational
databases work well with more fluid data models, such as in engineering parts and molecular modeling,
where the data is always changing.
A simple example of Data analysis is whenever we take any decision in our day-to-day life is by thinking
about what happened last time or what will happen by choosing that particular decision. This is nothing
but analyzing our past or future and making decisions based on it. For that, we gather memories of our
past or dreams of our future. So that is nothing but data analysis. Now same thing analyst does for business
purposes, is called Data Analysis.
To grow your business even to grow in your life, sometimes all you need to do is Analysis!
If your business is not growing, then you have to look back and acknowledge your mistakes and make a
plan again without repeating those mistakes. And even if your business is growing, then you have to look
forward to making the business to grow more. All you need to do is analyze your business data and
business processes.
Data Analysis Tools
Data analysis tools make it easier for users to process and manipulate data, analyze the relationships and
correlations between data sets, and it also helps to identify patterns and trends for interpretation. Here is a
complete list of tools used for data analysis in research.
Types of Data Analysis: Techniques and Methods
There are several types of Data Analysis techniques that exist based on business and technology.
However, the major Data Analysis methods are:
Text Analysis
Statistical Analysis
Diagnostic Analysis
Predictive Analysis
Prescriptive Analysis
Text Analysis
Text Analysis is also referred to as Data Mining. It is one of the methods of data analysis to discover a
pattern in large data sets using databases or data mining tools. It used to transform raw data into business
information. Business Intelligence tools are present in the market which is used to take strategic business
decisions. Overall it offers a way to extract and examine data and deriving patterns and finally
interpretation of the data.
Predictive Analysis
Predictive Analysis shows "what is likely to happen" by using previous data. The simplest data analysis
example is like if last year I bought two dresses based on my savings and if this year my salary is increasing
double then I can buy four dresses. But of course it's not easy like this because you have to think about
other circumstances like chances of prices of clothes is increased this year or maybe instead of dresses
you want to buy a new bike, or you need to buy a house!
So here, this Analysis makes predictions about future outcomes based on current or past data. Forecasting
is just an estimate. Its accuracy is based on how much detailed information you have and how much you
dig in it.
Prescriptive Analysis
Prescriptive Analysis combines the insight from all previous Analysis to determine which action to take
in a current problem or decision. Most data-driven companies are utilizing Prescriptive Analysis because
predictive and descriptive Analysis are not enough to improve data performance. Based on current
situations and problems, they analyze the data and make decisions.
Data Collection
After requirement gathering, you will get a clear idea about what things you have to measure and what
should be your findings. Now it's time to collect your data based on requirements. Once you collect your
data, remember that the collected data must be processed or organized for Analysis. As you collected data
from various sources, you must have to keep a log with a collection date and source of the data.
Data Cleaning
Now whatever data is collected may not be useful or irrelevant to your aim of Analysis, hence it should
be cleaned. The data which is collected may contain duplicate records, white spaces or errors. The data
should be cleaned and error free. This phase must be done before Analysis because based on data cleaning,
your output of Analysis will be closer to your expected outcome.
Data Analysis
Once the data is collected, cleaned, and processed, it is ready for Analysis. As you manipulate data, you
may find you have the exact information you need, or you might need to collect more data. During this
phase, you can use data analysis tools and software which will help you to understand, interpret, and derive
conclusions based on the requirements.
Data Interpretation
After analyzing your data, it's finally time to interpret your results. You can choose the way to express or
communicate your data analysis either you can use simply in words or maybe a table or chart. Then use
the results of your data analysis process to decide your best course of action.
Data Visualization
Data visualization is very common in your day to day life; they often appear in the form of charts and
graphs. In other words, data shown graphically so that it will be easier for the human brain to understand
and process it. Data visualization often used to discover unknown facts and trends. By observing
relationships and comparing datasets, you can find a way to find out meaningful information.
Summary:
Data analysis means a process of cleaning, transforming and modeling data to discover useful
information for business decision-making
Types of Data Analysis are Text, Statistical, Diagnostic, Predictive, Prescriptive Analysis
Data Analysis consists of Data Requirement Gathering, Data Collection, Data Cleaning, Data
Analysis, Data Interpretation, Data Visualization
DDL CREATE
DROP
ALTER
RENAME
TRUNCATE
DML SELECT
INSERT
UPDATE
DELETE
DCL GRANT
REVOKE
DDL in SQL
DDL allows you to create SQL statements to make operations with database data structures (schemas,
tables etc.).
DROP
DROP statement allows you to remove database, table, index or stored procedure.
Drop database example:
DROP DATABASE explainjava;
ALL RIGHTS RESERVED TO SVTI 117
Drop table example:
DROP TABLE user;
ALTER
ALTER is used to modify existing database data structures (database, table).
Alter table example:
ALTER TABLE user ADD COLUMN lastname VARCHAR(255) NOT NULL;
RENAME
RENAME command is used to rename SQL table.
Rename table example:
RENAME TABLE user TO student;
TRUNCATE
TRUNCATE operation is used to delete all table records.
Logically it’s the same as DELETE command.
DML in SQL
DML is a Data Manipulation Language, it’s used to build SQL queries to manipulate (select, insert, update,
delete etc.) data in the database.
This is DML commands list with examples:
SELECT
SELECT query is used to retrieve a data from SQL tables.
Example:
SELECT * FROM student;
INSERT
INSERT command is used to add new rows into the database table.
Example:
INSERT INTO student (name, lastname) VALUES ('Dmytro', 'Shvechikov');
UPDATE
UPDATE statement modifies records into the table.
Example:
UPDATE student SET name = 'Dima' WHERE lastname = 'Shvechikov';
DELETE
DELETE query removes entries from the table.
Example:
DELETE FROM student WHERE name = 'Dima';
GRANT
GRANT command gives permissions to SQL user account.
For example, I want to grant all privileges to ‘explainjava’ database for user ‘dmytro@localhost’.
Let’s create a user first:
CREATE USER 'dmytro'@'localhost' IDENTIFIED BY '123';
Then I can grant all privileges using GRANT statement:
GRANT ALL PRIVILEGES ON explainjava.* TO 'dmytro'@'localhost';
and we have to save changes using FLUSH command:
FLUSH PRIVILEGES;
REVOKE
REVOKE statement is used to remove privileges from user accounts.
Example:
REVOKE ALL PRIVILEGES ON explainjava.* FROM 'dmytro'@'localhost';
and save changes:
FLUSH PRIVILEGES;
TCL in SQL
TCL is a Transaction Control Language.
Its commands are used to manage transactions in SQL databases.
This is TCL commands list:
START TRANSACTION (BEGIN, BEGIN WORK)
START TRANSACTION is used to start a new SQL transaction.
BEGIN and BEGIN WORK are aliases for START TRANSACTION.
Example:
START TRANSACTION;
after that, you’re doing manipulations with a data (insert, update, delete) and at the end, you need to
commit a transaction.
COMMIT
As a mentioned above COMMIT command finishes transaction and stores all changes made inside of a
transaction.
Example:
START TRANSACTION;
INSERT INTO student (name, lastname) VALUES ('Dmytro', 'Shvechikov');
COMMIT;
ROLLBACK
ROLLBACK statement reverts all changes made in the scope of transaction.
Example:
START TRANSACTION;
INSERT INTO student (name, lastname) VALUES ('Dmytro', 'Shvechikov');
ROLLBACK;
DATA MODELING
Data modeling
Data modeling is the process of creating a visual representation of either a whole information system or
parts of it to communicate connections between data points and structures. The goal is to illustrate the
types of data used and stored within the system, the relationships among these data types, the ways the
data can be grouped and organized and its formats and attributes.
Data models are built around business needs. Rules and requirements are defined upfront through feedback
from business stakeholders so they can be incorporated into the design of a new system or adapted in the
iteration of an existing one.
Data can be modeled at various levels of abstraction. The process begins by collecting information about
business requirements from stakeholders and end users. These business rules are then translated into data
structures to formulate a concrete database design. A data model can be compared to a roadmap, an
architect’s blueprint or any formal diagram that facilitates a deeper understanding of what is being
designed.
Data modeling employs standardized schemas and formal techniques. This provides a common,
consistent, and predictable way of defining and managing data resources across an organization, or even
beyond.
Ideally, data models are living documents that evolve along with changing business needs. They play an
important role in supporting business processes and planning IT architecture and strategy. Data models
can be shared with vendors, partners, and/or industry peers.
Types of data models
Like any design process, database and information system design begins at a high level of abstraction and
becomes increasingly more concrete and specific. Data models can generally be divided into three
categories, which vary according to their degree of abstraction. The process will start with a conceptual
model, progress to a logical model and conclude with a physical model. Each type of data model is
discussed in more detail below:
Conceptual data models. They are also referred to as domain models and offer a big-picture view
of what the system will contain, how it will be organized, and which business rules are involved.
Conceptual models are usually created as part of the process of gathering initial project require-
ments. Typically, they include entity classes (defining the types of things that are important for the
business to represent in the data model), their characteristics and constraints, the relationships be-
tween them and relevant security and data integrity requirements. Any notation is typically simple.
Physical data models. They provide a schema for how the data will be physically stored within a
database. As such, they’re the least abstract of all. They offer a finalized design that can be imple-
mented as a relational database, including associative tables that illustrate the relationships among
entities as well as the primary keys and foreign keys that will be used to maintain those relationships.
Physical data models can include database management system (DBMS)-specific properties, includ-
ing performance tuning.
Two popular dimensional data models are the star schema, in which data is organized into facts
(measurable items) and dimensions (reference information), where each fact is surrounded by its
associated dimensions in a star-like pattern. The other is the snowflake schema, which resembles the star
schema but includes additional layers of associated dimensions, making the branching pattern more
complex.
Benefits of data modeling
Data modeling makes it easier for developers, data architects, business analysts, and other stakeholders to
view and understand relationships among the data in a database or data warehouse. In addition, it can:
Reduce errors in software and database development.
Increase consistency in documentation and system design across the enterprise.
Improve application and database performance.
Ease data mapping throughout the organization.
Improve communication between developers and business intelligence teams.
Ease and speed the process of database design at the conceptual, logical and physical levels.
erwin Data Modeler is a data modeling tool based on the Integration DEFinition for information
modeling (IDEF1X) data modeling language that now supports other notation methodologies, in-
cluding a dimensional approach.
Enterprise Architect is a visual modeling and design tool that supports the modeling of enterprise
information systems and architectures as well as software applications and databases. It’s based on
object-oriented languages and standards.
ER/Studio is database design software that’s compatible with several of today’s most popular data-
base management systems. It supports both relational and dimensional data modeling.
Free data modeling tools include open source solutions such as Open ModelSph
Three-level architecture
The objectives of the three-level architecture is to separate the user's view,
It allows independent customized user views: Each user should be able to access the same data, but
have a different customized view of the data. These should be independent: changes to one view should
not affect others.
It hides the physical storage details from users: Users should not have to deal with physical database
storage details.
The database administrator should be able to change the database storage structures without affecting
the users’ views.
The internal structure of the database should be unaffected by changes to the physical aspects of the
storage: For example, a changeover to a new disk.
Here is an example of how these two concepts might be combined in an ER data model: Prof. Ba
(entity) teaches (relationship) the Database Systems course (entity).
For the rest of this chapter, we will use a sample database called the COMPANY database to illustrate the
concepts of the ER model. This database contains information about employees, departments and projects.
Entities can be classified based on their strength. An entity is considered weak if its tables are existence
dependent.
That is, it cannot exist without a relationship with another entity
Its primary key is derived from the primary key of the parent entity
An entity is considered strong if it can exist apart from all of its related entities.
Kernels are strong entities.
A table without a foreign key or a table that contains a foreign key that can contain nulls is a strong
entity
Another term to know is entity type which defines a collection of similar entities.
An entity set is a collection of entities of an entity type at a particular point of time. In an entity relationship
diagram (ERD), an entity type is represented by a name in a box. For example, in Figure, the entity type
is EMPLOYEE.
.
Existence dependency
An entity’s existence is dependent on the existence of the related entity. It is existence-dependent if it has
a mandatory foreign key (i.e., a foreign key attribute that cannot be null). For example, in the COMPANY
database, a Spouse entity is existence -dependent on the Employee entity.
Kinds of Entities
You should also be familiar with different kinds of entities including independent entities, dependent
entities and characteristic entities. These are described below.
Independent entities
Independent entities, also referred to as kernels, are the backbone of the database. They are what other
tables are based on. Kernels have the following characteristics:
They are the building blocks of a database.
The primary key may be simple or composite.
The primary key is not a foreign key.
They do not depend on another entity for their existence.
If we refer back to our COMPANY database, examples of an independent entity include the Customer
table, Employee table or Product table.
Dependent entities
Dependent entities, also referred to as derived entities, depend on other tables for their meaning. These
entities have the following characteristics:
Dependent entities are used to connect two kernels together.
They are said to be existence dependent on two or more tables.
Many to many relationships become associative tables with at least two foreign keys.
They may contain other attributes.
The foreign key identifies each associated table.
There are three options for the primary key:
1. Use a composite of foreign keys of associated tables if unique
2. Use a composite of foreign keys and a qualifying column
Characteristic entities
Characteristic entities provide more information about another table. These entities have the following
characteristics:
They represent multivalued attributes.
They describe other entities.
They typically have a one to many relationship.
The foreign key is used to further identify the characterized table.
Options for primary key are as follows:
1. Use a composite of foreign key plus a qualifying column
2. Create a new simple primary key. In the COMPANY database, these might include:
Employee (EID, Name, Address, Age, Salary) – EID is the simple primary key.
EmployeePhone (EID, Phone) – EID is part of a composite primary key. Here, EID
is also a foreign key.
Attributes
Each entity is described by a set of attributes (e.g., Employee = (Name, Address, Birthdate (Age), Salary).
Each attribute has a name, and is associated with an entity and a domain of legal values. However, the
information about attribute domain is not presented on the ERD.
In the entity relationship diagram, shown in Figure, each attribute is represented by an oval with a name
inside.
Types of Attributes
There are a few types of attributes you need to be familiar with. Some of these are to be left as is, but some
need to be adjusted to facilitate representation in the relational model. This first section will discuss the
types of attributes. Later on we will discuss fixing the attributes to fit correctly into the relational model.
Simple attributes
Simple attributes are those drawn from the atomic value domains; they are also called single-valued
attributes. In the COMPANY database, an example of this would be: Name = {John} ; Age = {23}
Composite attributes
Composite attributes are those that consist of a hierarchy of attributes. Using our database example, and
shown in Figure, Address may consist of Number, Street and Suburb. So this would be written as →
Address = {59 + ‘Meek Street’ + ‘Kingsford’}
Derived attributes
Derived attributes are attributes that contain values calculated from other attributes. An example of this
can be seen in Figure. Age can be derived from the attribute Birthdate. In this situation, Birthdate is called
a stored attribute, which is physically saved to the database.
Keys
An important constraint on an entity is the key. The key is an attribute or a group of attributes whose values
can be used to uniquely identify an individual entity in an entity set.
Types of Keys
There are several types of keys. These are described below.
From our COMPANY database example, if the entity is Employee(EID, First Name, Last Name, SIN,
Address, Phone, BirthDate, Salary, DepartmentID), possible candidate keys are:
EID, SIN
First Name and Last Name – assuming there is no one else in the company with the same name
Last Name and DepartmentID – assuming two people with the same last name don’t work in the
same department
Composite key
A composite key is composed of two or more attributes, but it must be minimal.
Using the example from the candidate key section, possible composite keys are:
First Name and Last Name – assuming there is no one else in the company with the same name
Last Name and Department ID – assuming two people with the same last name don’t work in the
same department
Primary key
The primary key is a candidate key that is selected by the database designer to be used as an identifying
mechanism for the whole entity set. It must uniquely identify tuples in a table and not be null. The primary
key is indicated in the ER model by underlining the attribute.
A candidate key is selected by the designer to uniquely identify tuples in a table. It must not be null.
A key is chosen by the database designer to be used as an identifying mechanism for the whole entity
set. This is referred to as the primary key. This key is indicated by underlining the attribute in the ER
model.
Secondary key
A secondary key is an attribute used strictly for retrieval purposes (can be composite), for example: Phone
and Last Name.
Alternate key
Alternate keys are all candidate keys not chosen as the primary key.
Foreign key
A foreign key (FK) is an attribute in a table that references the primary key in another table OR it can be
null. Both foreign and primary keys must be of the same data type.
In the COMPANY database example below, DepartmentID is the foreign key:
Employee(EID, First Name, Last Name, SIN, Address, Phone, BirthDate, Salary, DepartmentID)
Nulls
A null is a special symbol, independent of data type, which means either unknown or inapplicable. It does
not mean zero or blank. Features of null include:
No data entry
Not permitted in the primary key
Should be avoided in other attributes
Can represent
NOTE: The result of a comparison operation is null when either argument is null. The result of an
arithmetic operation is null when either argument is null (except functions that ignore nulls).
To begin, find all employees (emp#) in Sales (under the jobName column) whose salary plus commission
are greater than 30,000.
SELECT emp# FROM Salary_tbl
WHERE jobName = Sales AND
(commission + salary) > 30,000 –> E10 and E12
This result does not include E13 because of the null value in the commission column. To ensure that the
row with the null value is included, we need to look at the individual fields. By adding commission and
salary for employee E13, the result will be a null value. The solution is shown below.
SELECT emp# FROM Salary_tbl
WHERE jobName = Sales AND
(commission > 30000 OR
salary > 30000 OR
(commission + salary) > 30,000 –>E10 and E12 and E13
Relationships
Relationships are the glue that holds the tables together. They are used to connect related information
between tables.
Relationship strength is based on how the primary key of a related entity is defined. A weak, or non-
identifying, relationship exists if the primary key of the related entity does not contain a primary key
component of the parent entity. Company database examples include:
Customer(CustID, CustName)
Order(OrderID, CustID, Date)
A strong, or identifying, relationship exists when the primary key of the related entity contains the primary
key component of the parent entity. Examples include:
Course(CrsCode, DeptCode, Description)
Class(CrsCode, Section, ClassTime…)
Types of Relationships
ALL RIGHTS RESERVED TO SVTI 130
Below are descriptions of the various types of relationships.
Figure shows another another aspect of the M:N relationship where an employee has different start dates
for different projects. Therefore, we need a JOIN table that contains the EID, Code and StartDate.
Ternary Relationships
A ternary relationship is a relationship type that involves many to many relationships between three
tables.
Refer to Figure for an example of mapping a ternary relationship type. Note n-ary means multiple tables
in a relationship. (Remember, N = many.)
For each n-ary (> 2) relationship, create a new relation to represent the relationship.
The primary key of the new relation is a combination of the primary keys of the participating entities
that hold the N (many) side.
In most cases of an n-ary relationship, all the participating entities hold a many side.
NORMALIZATION
Normalization
Normalization is a database design technique that reduces data redundancy and eliminates undesirable
characteristics like Insertion, Update and Deletion Anomalies. Normalization rules divides larger tables
into smaller tables and links them using relationships. The purpose of Normalisation in SQL is to eliminate
redundant (repetitive) data and ensure data is stored logically.
The inventor of the relational model Edgar Codd proposed the theory of normalization of data with the
introduction of the First Normal Form, and he continued to extend theory with Second and Third Normal
Form. Later he joined Raymond F. Boyce to develop the theory of Boyce-Codd Normal Form.
Database Normal Forms
Here is a list of Normal Forms in SQL:
What is Database SQL
1NF (First Normal Form)
2NF (Second Normal Form)
3NF (Third Normal Form)
BCNF (Boyce-Codd Normal Form)
4NF (Fourth Normal Form)
5NF (Fifth Normal Form)
6NF (Sixth Normal Form)
The Theory of Data Normalization in MySQL server is still being developed further. For example, there
are discussions even on 6th Normal Form. However, in most practical applications, normalization
achieves its best in 3rd Normal Form. The evolution of Normalization in SQL theories is illustrated
below-
Hence, we require both Full Name and Address to identify a record uniquely. That is a composite key.
Let's move into second normal form 2NF
It is clear that we can't move forward to make our simple database in 2nd Normalization form unless we
partition the table above.
We have divided our 1NF table into two tables viz. Table 1 and Table2. Table 1 contains member
information. Table 2 contains information on movies rented.
We have introduced a new column called Membership_id which is the primary key for table 1. Records
can be uniquely identified in Table 1 using membership id
You will only be able to insert values into your foreign key that exist in the unique key in the parent table.
This helps in referential integrity.
The above problem can be overcome by declaring membership id from Table2 as foreign key of
membership id from Table1
Now, if somebody tries to insert a value in the membership id field that does not exist in the parent table,
an error will be shown!
A transitive functional dependency is when changing a non-key column, might cause any of the other non-
key columns to change
3NF Example
Below is a 3NF example in SQL database:
We have again divided our tables and created a new table which stores Salutations.
There are no transitive functional dependencies, and hence our table is in 3NF
In Table 3 Salutation ID is primary key, and in Table 1 Salutation ID is foreign to primary key in Table 3
Now our little example is at a level that cannot further be decomposed to attain higher normal form types
of normalization in DBMS. In fact, it is already in higher normalization forms. Separate efforts for moving
into next levels of normalizing data are normally needed in complex databases. However, we will be
discussing next levels of normalisation in DBMS in brief in the following.
Summary
Database designing is critical to the successful implementation of a database management system
that meets the data requirements of an enterprise system.
Normalization in DBMS is a process which helps produce database systems that are cost-effective
and have better security models.
Functional dependencies are a very important component of the normalize data process
Most database systems are normalized database up to the third normal forms in DBMS.
A primary key uniquely identifies are record in a Table and cannot be null
A foreign key helps connect table and references a primary key
Denormalization in Databases
Denormalization is a database optimization technique in which we add redundant data to one or more
tables. This can help us avoid costly joins in a relational database. Note that denormalization does not
mean not doing normalization. It is an optimization technique that is applied after doing normalization.
In a traditional normalized database, we store data in separate logical tables and attempt to minimize
redundant data. We may strive to have only one copy of each piece of data in database.
For example, in a normalized database, we might have a Courses table and a Teachers table. Each entry
in Courses would store the teacherID for a Course but not the teacherName. When we need to retrieve
a list of all Courses with the Teacher’s name, we would do a join between these two tables.
In some ways, this is great; if a teacher changes his or her name, we only have to update the name in
one place.
The drawback is that if tables are large, we may spend an unnecessarily long time doing joins on tables.
Denormalization, then, strikes a different compromise. Under denormalization, we decide that we’re
okay with some redundancy and some extra effort to update the database in order to get the efficiency
advantages of fewer joins.
Pros of Denormalization:-
1. Retrieving data is faster since we do fewer joins
2. Queries to retrieve can be simpler(and therefore less likely to have bugs),
since we need to look at fewer tables.
Cons of Denormalization:-
1. Updates and inserts are more expensive.
2. Denormalization can make update and insert code harder to write.
3. Data may be inconsistent . Which is the “correct” value for a piece of data?
4. Data redundancy necessitates more storage.
RELATIONSHIPS
Introduction to Database Relationships
The database terms relational and relationship describe the way that data in tables are connected. A
relational database consists of a series of two or more tables linked by a specific key. A relational
database differs from unstructured databases, which are common in big data initiatives. Relational
databases tend to require strict rules about how tables are defined and what constitutes a valid
relationship among tables.
One-to-one relationships occur when each entry in the first table has only one counterpart in the
second table. One-to-one relationships are rarely used because it is often more efficient to put all
the information in a single table. Some database designers take advantage of this relationship by
creating tables that contain a subset of the data from another table.
One-to-many relationships are the most common type of database relationship. They occur when
each record in Table A corresponds to one or more records in Table B, but each record in Table B
corresponds to only one record in Table A. For example, the relationship between a Teachers table
and a Students table in an elementary school database would likely be a one-to-many relationship
because each student has only one teacher, but each teacher has several students. This one-to-many
design helps eliminate duplicated data.
Many-to-many relationships occur when each record in Table A corresponds to one or more
records in Table B, and each record in Table B corresponds to one or more records in Table A. For
example, the relationship between a Teachers table and a Courses table would likely be many-to-
many because each teacher may instruct more than one course, and each course may have more
than one instructor.
Consider the example of the Teachers and Students tables. The Teachers table contains an ID, a name,
and a course column:
The Students table includes an ID, name, and a foreign key column:
StudentID Student_Name Teacher_FK
The column Teacher_FK in the Students table references the primary key value of an instructor in the
Teachers table. Frequently, database designers use PK or FK in the column name to identify a primary
key or foreign key column.
These two tables illustrate a one-to-many relationship between the teachers and the students.
Implementing relationships
Depending on your database, you'll implement relationships between tables in different ways. Microsoft
Access provides a wizard that allows you to link tables and also enforce referential integrity.
If you are writing SQL directly, first create the table Teachers, declaring an ID column to be the primary
key:
When you create the Students table, you declare the Teacher_FK column to be a foreign key referenc-
ing the InstructorID column in the Teachers' table:
CREATE TABLE Students (
StudentID INT AUTO_INCREMENT PRIMARY KEY,
Student_Name VARCHAR(100), Teacher_FK INT,
FOREIGN KEY (Teacher_FK) REFERENCES Teachers(InstructorID) )
);
For example, this JOIN condition returns Student_Name, Teacher_Name, and Course, where the foreign
key in the Students table matches the primary key in the Teachers table:
SQL PERFORMANCE
SQL - Indexes
Indexes are special lookup tables that the database search engine can use to speed up data retrieval.
Simply put, an index is a pointer to data in a table. An index in a database is very similar to an index in
the back of a book.
For example, if you want to reference all pages in a book that discusses a certain topic, you first refer to
the index, which lists all the topics alphabetically and are then referred to one or more specific page
numbers.
An index helps to speed up SELECT queries and WHERE clauses, but it slows down data input, with
the UPDATE and the INSERT statements. Indexes can be created or dropped with no effect on the data.
Creating an index involves the CREATE INDEX statement, which allows you to name the index, to
specify the table and which column or columns to index, and to indicate whether the index is in an
ascending or descending order.
Indexes can also be unique, like the UNIQUE constraint, in that the index prevents duplicate entries in
the column or combination of columns on which there is an index.
Single-Column Indexes
A single-column index is created based on only one table column. The basic syntax is as follows.
CREATE INDEX index_name
ON table_name (column_name);
Unique Indexes
Unique indexes are used not only for performance, but also for data integrity. A unique index does not
allow any duplicate values to be inserted into the table. The basic syntax is as follows.
CREATE UNIQUE INDEX index_name
on table_name (column_name);
Composite Indexes
A composite index is an index on two or more columns of a table. Its basic syntax is as follows.
CREATE INDEX index_name
on table_name (column1, column2);
Whether to create a single-column index or a composite index, take into consideration the column(s) that
you may use very frequently in a query's WHERE clause as filter conditions.
Should there be only one column used, a single-column index should be the choice. Should there be two
or more columns that are frequently used in the WHERE clause as filters, the composite index would be
the best choice.
Implicit Indexes
Implicit indexes are indexes that are automatically created by the database server when an object is
created. Indexes are automatically created for primary key constraints and unique constraints.
QUERY PERFORMANCE
The following guidelines can help you optimize the performance of a local Access database — a database
that is stored on a local hard disk drive, rather than on a network.
Turn off Name AutoCorrect
Set the database to compact and repair automatically
Open the database in exclusive mode
Turn off AutoCorrect options
Note: You do not need to turn off all the AutoCorrect options to see a benefit, but the more AutoCorrect
options that you turn off, the bigger the benefit.
Transaction Properties
A database management system (DBMS) is considered a relational database management system
(RDBMS) if it follows the transactional properties, ACID.
A: Atomicity
C: Consistency
I: Isolation
D: Durability
The SQL Server takes care of the Atomicity, Consistency, and Durability of the system, and the user has
to care about the Isolation property of the transaction. The meaning of each of these properties is described
below, as it applies to a transaction.
Atomicity
Transaction work should be atomic, which means all the work is one unit. If the user performs a transition,
either the transaction should complete and perform all the asked operations, or it should fail and don’t do
anything. Atomicity deals with the transaction process and an RDBMS transaction does not leave the work
incomplete.
Consistency
After the transaction is completed, the database should not be left in an inconsistent state, which means
the data on which transaction is applied must be logically correct, according to the rules of the system.
Isolation
If two transactions are applied on a similar database, then both the transaction should be isolated from
each other, and the user must see the result. It can also be defined as a transaction that should see the data
only after or before the concurrent transaction process is completed, which means if a one transaction
process is in between, the other transaction process should wait until the first transaction is completed.
For instance, if A performs a transaction process on data d1, and before the transaction process gets
completed, B also performs another transaction process on the same data d1. Here, the isolation property
will isolate the transaction process of A and B, and the transaction process of B will only start after the
transaction process of A gets completed.
Durability
Even if the system fails, the transaction should be persistent, which means, if the system fails during a
transaction process, the transaction should be dropped, too, without affecting the data.
Dirty Read
This problem occurs when another process reads the changed, but uncommitted data. For instance, if one
process has changed data but not committed it yet, another process is able to read the same data. This leads
to the inconsistent state for the reader.
Lost Updates
This problem occurs when two processes try to manipulate the same data simultaneously. This problem
can lead to data loss, or the second process might overwrite the first processs change.
Non-repeatable Reads
This problem occurs when one process is reading the data, and another process is writing the data. In non-
repeatable reads, the first process reading the value might get two different values, as the changed data is
read a second time because the second process changes the data.
Phantom Reads
If two same queries executed by two users show different output, then it would be a Phantom Read
problem. For instance, If user A select a query to read some data, at the same time the user B insert some
new data but the user A only get able to read the old data at the first attempt, but when user A re-query
the same statement then he/she gets a different set of data.
Note that readers are users are performing the SELECT operations. Writers are users are performing
INSERT, ALTER, UPDATE, S.E.T. operations.
Isolation Level
When we connect to a SQL server database, the application can submit queries to the database with one
of five different isolation levels. These levels are:
Read Uncommitted
Read Committed
Repeatable Read
Serializable
Snapshot
Read Uncommitted
This is the first level of isolation, and it comes under the pessimistic model of concurrency. In Read
Uncommitted, one transaction is allowed to read the data that is about to be changed by the commit of
another process. Read Uncommitted allows the dirty read problem.
Read Committed
This is the second level of isolation and also falls under the pessimistic model of concurrency. In the Read
Committed isolation level, we are only allowed to read data that is committed, which means this level
eliminates the dirty read problem. In this level, if you are reading data then the concurrent transactions
that can delete or write data, some work is blocked until other work is complete.
Repeatable Read
The Repeatable Read isolation level is similar to the Read Committed level and eliminates the Non-
Repeatable Read problem. In this level, the transaction has to wait till another transaction's update or read
query is complete. But if there is an insert transaction, it does not wait for anyone. This can lead to the
Phantom Read problem.
Serializable
This is the highest level of isolation in the pessimistic model. By implementing this level of isolation, we
can prevent the Phantom Read problem. In this level of isolation, we can ask any transaction to wait until
the current transaction completes.
Snapshot
Snapshot follows the optimistic model of concurrency, and this level of isolation takes a snapshot of the
current data and uses it as a copy for the different transactions. Here each transaction has its copy of data,
so if a user tries to perform a transaction like an update or insert, it asks him to re-verify all the operation
before the process gets started executing.
Conclusion
Concurrency occurs when two transactions operate currently on the same set of data. Concurrency can
then lead to data inconsistency and abnormal behaviour for a transaction. RDBMS transactions have four
properties, which are known as ACID, that ensure consistency of work. There are four major common
concurrency problems that can be solved by using two models of concurrency: pessimistic and optimistic.
We can complete work in SQL Server with any of these five types of isolation levels.
DATABASE OBJECTS
The system views are views that contain internal information about a Database. The master database for
example contains information about the SQL Server itself, while the msdb database contain information
about the SQL Server agent and each database has its own system views/tables.
In this article we will show how to get the list of tables, views, stored procedures, how to get a list of
tables of all the databases, how to find a table in multiple datatabases, how to get the list of users, logins,
mapped logins, how to detect a fragmentation in a table and more.
Let’s start with some common questions about databases that can be solved with the system
views/tables/functions:
Option 1
You can use schema views (the INFORMATION_CHEMA.TABLES) or the sysobjects views directly.
According to the books, it is better to use the INFORMATION_SCHEMA views because the internal
structure will not change in the future. The sysobjects view contains useful information about the different
database objects.
Xtype is the type of object and the possible values are:
SQ = Service Queue
TA = Assembly (CLR) DML trigger
TF = Table-valued-Function
TR = Trigger
TT = Table Type
U = User Table
UQ = Unique Constraint
V = View
X = Extended stored procedure
[INFORMATION_SCHEMA].[VIEWS] contains information about the views or you can find the
information in the sysobjects view.
How can I get the list of procedures in a database?
There are 2 options to solve this problem:
SELECT *
FROM sysobjects
WHERE xtype = 'P'
Crdate is the creation date and sysobjects is the view that contains most of the database objects including
tables, views, stored procedures and functions.
How can I get the list of all the tables in all the databases?
The sp_MSforeachdb, is a very useful stored procedure that helps to work with all the databases. For some
reason, this stored procedure is not documented.
The ? is the database name. It will show the result of the query in each database.
How can I search a table in all the databases?
This is a classical problem. The user created a table, but he does not remember where it was created and
there are multiple databases where we need to search.
The following example shows how to find a table named test in all the SQL Server databases. The query
will show the database(s) and the table.
ALL RIGHTS RESERVED TO SVTI 150
DECLARE @cmd varchar(8000)
SELECT @cmd = 'USE ? SELECT ''?'',name FROM sysobjects WHERE xtype = ''U'' and name=''test'''
EXEC sp_MSforeachdb @cmd
How can I get the list of stored procedures names and their code?
The syscomments view contains very useful information about the stored procedure, triggers, checks and
other SQL Server objects. You can check the code of your procedures, triggers and other objects. The
sysobjects contains the stored procedure name and the syscomments the code. This query is very useful
to find some words in multiple stored procedures at the same time.
How can I get the creation date of a specific SQL Server Login?
The Login allows to login to the SQL Server database and the database user contains permissions to access
to specific databases. The following query shows the creation Date of a specific Login:
select * from
[sys].[syslogins]
where name='sa'
How can I get the Login and the user mapped in all the databases?
This information is in the sys.database.principals and syss,server.principals. You will find the Login and
the database user mapped to it.
DECLARE @cmd varchar(8000)
SELECT @cmd =
If the fragmentation percentage is higher than 30%, it is better to rebuild the index. If it is lower than 30%,
you can just reorganize the index.
How can I get the information about the SQL Server sessions?
The [sys].[dm_exec_sessions] view contains useful information about the sessions like the start time, end
time, login name, NT domain, program used and more.
SELECT *
FROM [sys].[dm_exec_sessions]
How can I get information about the size in MB and location of a backup?
You can also find very useful information about the backup file size and the path of the backup using the
backupfile system table. The following sample shows the size of the backups in MB and the path where
it is located. This information is stored in the msdn database. The backup file_size is stored in bytes, that
is why it is necessary to convert the value to MB.
SELECT
[file_size]/1024/1024 as Size_in_mb
,[physical_name]
FROM [msdb].[dbo].[backupfile]
How can I get information about creation date and modification date of a SQL Server Job?
There is a lot of information about SQL jobs in the MSDB database, dbo.sysjobs table. All the information
related to the agent is stored in the MSDB database.
SELECT
[date_created]
,[date_modified]
FROM [msdb].[dbo].[sysjobs]