You are on page 1of 14

Database Connection and Executing Queries

Imports System
Imports System.Data
Imports System.Data.OleDb
Public Class clsDatabaseConnection
‘Microsoft.ACE.OLEDB.12.0 for accdb file
Private conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" &
Application.StartupPath & "\dbName.mdb" )

Public Function Execute(ByVal SQLCommand As String) As DataTable


Try
conn.Open()
Dim myAdapter As New OleDbDataAdapter(SQLCommand, conn)
Dim myDataTable As New DataTable

myAdapter.Fill(myDataTable)
Catch ex As Exception
MsgBox("Error: " & ex.ToString)
Finally
conn.Close()
End Try
Return myDataTable
End Function

Public Function doScalar(ByVal sql As String) As String


Dim count As String = ""
Try
conn.Open()
Dim cmd As OleDbCommand = New OleDbCommand(sql, conn)
count = cmd.ExecuteScalar()
Catch
Finally
conn.Close()
End Try
Return count
End Function
End Class
Clearing Controls
For Each ctrl As Control In root.Controls
If TypeOf ctrl Is TextBox Then
CType(ctrl, TextBox).Text = String.Empty
End If
Next ctrl

Filling ListView
Public Sub fillListView(ByVal lv As ListView, ByVal dt As DataTable)
Dim dtrow As DataRow
lv.Items.Clear()

For Each dtrow In dt.Rows


Dim lvrow As ListViewItem = New ListViewItem
lvrow.Text = dtrow(0).ToString
For ctr As Integer = 1 To dt.Columns.Count - 1
lvrow.SubItems.Add(dtrow(ctr).ToString)
Next
lv.Items.Add(lvrow)
Next
End Sub

Computing Age
Public Function computeAge(ByVal bday As Date)
Dim getData As String = ""

'computes the age based on the birthdate:


getData = Math.Floor(DateDiff("d", bday, Date.Now) / 365.25)

Return getData
End Function

Handling Number Keypress


Public Sub NumberKeyPress(ByVal objEvent As System.Windows.Forms.KeyPressEventArgs)
If Not (Char.IsNumber(Convert.ToChar(objEvent.KeyChar)) Or objEvent.KeyChar = vbBack) Then
objEvent.Handled = True
End If
End Sub
Generating Random Numbers
Public Function GenerateRandomNumber() As Integer
Dim RandomClass As New Random()
Dim RandomNumber As Integer
RandomNumber = RandomClass.Next(1, 1000000000)

Return RandomNumber
End Function

Scanning through the ListView and determine the selected row


with its index
Public Sub scan(ByVal LV As ListView)
Dim ctr As Integer
Dim key As String = ""
For ctr = 0 To LV.Items.Count - 1
LV.Focus()
If LV.Items(ctr).Selected Then
key = LV.Items(ctr).Text
End If
Next
End Sub

Adding Columns to ListView Programmatically


lvw.Columns.Add("ColumnName1", 140, HorizontalAlignment.Left)
lvw.Columns.Add("ColumnName2", 300, HorizontalAlignment.Left)
lvw.Columns.Add("ColumnName3", 50, HorizontalAlignment.Center)
lvw.Columns.Add("ColumnName4", 300, HorizontalAlignment.Center)
lvw.Columns.Add("ColumnName5", 250, HorizontalAlignment.Center)

SQL Commands
The INSERT INTO Statement
The INSERT INTO statement is used to insert a new row in a table.

SQL INSERT INTO Syntax

It is possible to write the INSERT INTO statement in two forms.

The first form doesn't specify the column names where the data will be inserted, only their values:

INSERT INTO table_name


VALUES (value1, value2, value3,...)

The second form specifies both the column names and the values to be inserted:

INSERT INTO table_name (column1, column2, column3,...)


VALUES (value1, value2, value3,...)

The UPDATE Statement


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

SQL UPDATE Syntax

UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value

The DELETE Statement


The DELETE statement is used to delete rows in a table.

SQL DELETE Syntax

DELETE FROM table_name


WHERE some_column=some_value

 SORTING QUERY RESULTS


 SQL ORDER BY
 is used to sort the result
Syntax:
WHERE condition
ORDER BY column-name [ASC/DESC]

ASC- sorts in ascending order


DESC – sorts in descending order
 ORDER BY Examples
 Display territories in alphabetical order.
SELECT * from territories ORDER BY TerritoryDescription
 Display territories where RegionID is in descending order.
SELECT RegionID, TerritoryID, TerritoryDescription FROM Territories ORDER BY
RegionID DESC
 ORDER BY Examples
 Display in descending order the price and products that starts with ‘L’.
SELECT ProductName, UnitPrice
FROM Products
WHERE ProductName LIKE 'L%'
ORDER BY UnitPrice DESC
 HAVING Clause
 Defines the condition that is then applied to groups of rows
Syntax:
SELECT
FROM
GROUP BY
HAVING condition
Note:
condition contains an aggregate function or constants
 Aggregate Functions
 Having Examples
 Display the stores that have a sale of more than 100
SELECT stor_id, sum(qty)
FROM sales
GROUP BY stor_id
HAVING sum(qty)>100
 Having Examples
 Find book type and average price for that type. Only show groups if the average price in
that group is greater than $12
SELECT type, avg(price) [Average Price]
FROM titles
GROUP BY type
HAVING avg(price) > 12
 COMPUTE Clause
 Uses aggregate functions to calculate summary values that appear as additional rows in the
result of a query
Syntax:
SELECT
FROM
WHERE
COMPUTE aggregate function
 COMPUTE Examples
 Display the title of the book whose price is greater than 20. Compute the sum of the price
of the books.
SELECT title, price
FROM Titles
WHERE price >20
COMPUTE sum(price)

SQL Aggregate Functions


SQL aggregate functions return a single value, calculated from values in a column.
Useful aggregate functions:

 AVG() - Returns the average value


 COUNT() - Returns the number of rows
 FIRST() - Returns the first value
 LAST() - Returns the last value
 MAX() - Returns the largest value
 MIN() - Returns the smallest value
 SUM() - Returns the sum

SQL INNER JOIN Keyword


The INNER JOIN keyword return rows when there is at least one match in both tables.

SQL INNER JOIN Syntax

SELECT column_name(s)
FROM table_name1
INNER JOIN table_name2
ON table_name1.column_name=table_name2.column_name

String Manipulation
The String class of the .NET framework provides many built-in methods to facilitate the comparison and manipulation of strings.
It is now a trivial matter to get data about a string, or to create new strings by manipulating current strings. The Visual Basic .NET
language also has inherent methods that duplicate many of these functionalities.

Types of String Manipulation Methods

In this section you will read about several different ways to analyze and manipulate your strings. Some of the methods are a part
of the Visual Basic language, and others are inherent in the String class.

Visual Basic .NET methods are used as inherent functions of the language. They may be used without qualification in your code.
The following example shows typical use of a Visual Basic .NET string-manipulation command:

Copy
Dim aString As String = "SomeString"
Dim bString As String
bString = Mid(aString, 3, 3)

In this example, the Mid function performs a direct operation on aString and assigns the value to bString.

You can also manipulate strings with the methods of the String class. There are two types of methods in String: shared methods
and instance methods.

A shared method is a method that stems from the String class itself and does not require an instance of that class to work. These
methods can be qualified with the name of the class (String) rather than with an instance of the String class. For example:

Copy
Dim aString As String
bString = String.Copy("A literal string")
In the preceding example, the String.Copy method is a static method, which acts upon an expression it is given and assigns the
resulting value to bString.

Instance methods, by contrast, stem from a particular instance of String and must be qualified with the instance name. For
example:

Copy
Dim aString As String = "A String"
Dim bString As String
bString = aString.SubString(2,6) ' bString = "String"

In this example, the SubString method is a method of the instance of String (that is, aString). It performs an operation on
aString and assigns that value to bString.

Nothing and Strings

The Visual Basic runtime and the .NET Framework evaluate Nothing differently when it comes to strings. Consider the following
example:

Copy
Dim MyString As String = "This is my string"
Dim stringLength As Integer
' Explicitly set the string to Nothing.
MyString = Nothing
' stringLength = 0
stringLength = Len(MyString)
' This line, however, causes an exception to be thrown.
stringLength = MyString.Length

The Visual Basic .NET runtime evaluates Nothing as an empty string; that is, "". The .NET Framework, however, does not, and will
throw an exception whenever an attempt is made to perform a string operation on Nothing.

Comparing Strings

You can compare two strings by using the String.Compare method. This is a static, overloaded method of the base string class.
In its most common form, this method can be used to directly compare two strings based on their alphabetical sort order. This is
similar to the Visual Basic StrComp Function function. The following example illustrates how this method is used:

Copy
Dim myString As String = "Alphabetical"
Dim secondString As String = "Order"
Dim result As Integer
result = String.Compare (myString, secondString)

This method returns an integer that indicates the relationship between the two compared strings based on the sorting order. A
positive value for the result indicates that the first string is greater than the second string. A negative result indicates the first
string is smaller, and zero indicates equality between the strings. Any string, including an empty string, evaluates to greater than
a null reference.

Additional overloads of the String.Compare method allow you to indicate whether or not to take case or culture formatting into
account, and to compare substrings within the supplied strings. For more information on how to compare strings, see
String.Compare Method. Related methods include String.CompareOrdinal Method and String.CompareTo Method.

Searching for Strings Within Your Strings


There are times when it is useful to have data about the characters in your string and the positions of those characters within
your string. A string can be thought of as an array of characters (Char instances); you can retrieve a particular character by
referencing the index of that character through the Chars property. For example:

Copy
Dim myString As String = "ABCDE"
Dim myChar As Char
myChar = myString.Chars(3) ' myChar = "D"

You can use the String.IndexOf method to return the index where a particular character is encountered, as in the following
example:

Copy
Dim myString As String = "ABCDE"
Dim myInteger As Integer
myInteger = myString.IndexOf("D") ' myInteger = 3

In the previous example, the IndexOf method of myString was used to return the index corresponding to the first instance of
the character "C" in the string. IndexOf is an overloaded method, and the other overloads provide methods to search for any of
a set of characters, or to search for a string within your string, among others. The Visual Basic .NET command InStr also allows
you to perform similar functions. For more information of these methods, see String.IndexOf Method and InStr Function. You can
also use the String.LastIndexOf Method to search for the last occurrence of a character in your string.

Creating New Strings from Old

When using strings, you may want to modify your strings and create new ones. You may want to do something as simple as
convert the entire string to uppercase, or trim off trailing spaces; or you may want to do something more complex, such as
extracting a substring from your string. The System.String class provides a wide range of options for modifying, manipulating,
and making new strings out of your old ones.

To combine multiple strings, you can use the concatenation operators (& or +). You can also use the String.Concat Method to
concatenate a series of strings or strings contained in objects. An example of the String.Concat method follows:

Copy
Dim aString As String = "A"
Dim bString As String = "B"
Dim cString As String = "C"
Dim dString As String = "D"
Dim myString As String
' myString = "ABCD"
myString = String.Concat(aString, bString, cString, dString)

You can convert your strings to all uppercase or all lowercase strings using either the Visual Basic .NET functions UCase Function
and LCase Function or the String.ToUpper Method and String.ToLower Method methods. An example is shown below:

Copy
Dim myString As String = "UpPeR oR LoWeR cAsE"
Dim newString As String
' newString = "UPPER OR LOWER CASE"
newString = UCase(myString)
' newString = "upper or lower case"
newString = LCase(myString)
' newString = "UPPER OR LOWER CASE"
newString = myString.ToUpper
' newString = "upper or lower case"
newString = myString.ToLower
The String.Format method and the Visual Basic .NET Format command can generate a new string by applying formatting to a
given string. For information on these commands, see Format Function or String.Format Method.

You may at times need to remove trailing or leading spaces from your string. For instance, you might be parsing a string that
had spaces inserted for the purposes of alignment. You can remove these spaces using the String.Trim Method function, or the
Visual Basic .NET Trim function. An example is shown:

Copy
Dim spaceString As String = _
" This string will have the spaces removed "
Dim oneString As String
Dim twoString As String
' This removes all trailing and leading spaces.
oneString = spaceString.Trim
' This also removes all trailing and leading spaces.
twoString = Trim(spaceString)

If you only want to remove trailing spaces, you can use the String.TrimEnd Methodor the RTrim function, and for leading spaces
you can use the String.TrimStart Method or the LTrim function. For more details, seeLTrim, RTrim, and Trim Functions functions.

The String.Trim functions and related functions also allow you to remove instances of a specific character from the ends of your
string. The following example trims all leading and trailing instances of the "#" character:

Copy
Dim myString As String = "#####Remove those!######"
Dim oneString As String
OneString = myString.Trim("#")

You can also add leading or trailing characters by using the String.PadLeft Method or the String.PadRight Method.

If you have excess characters within the body of your string, you can excise them by using the String.Remove Method, or you can
replace them with another character using the String.Replace Method. For example:

Copy
Dim aString As String = "This is My Str@o@o@ing"
Dim myString As String
Dim anotherString As String
' myString = "This is My String"
myString = aString.Remove(14, 5)
' anotherString = "This is Another String"
anotherString = myString.Replace("My", "Another")

You can use the String.Replace method to replace either individual characters or strings of characters. The Visual Basic .NET Mid
Statement can also be used to replace an interior string with another string.

You can also use the String.Insert Method to insert a string within another string, as in the following example:

Copy
Dim aString As String = "This is My Stng"
Dim myString As String
' Results in a value of "This is My String".
myString = aString.Insert(13, "ri")

The first parameter that the String.Insert method takes is the index of the character the string is to be inserted after, and the
second parameter is the string to be inserted.
You can concatenate an array of strings together with a separator string by using the String.Join Method. Here is an example:

Copy
Dim shoppingItem(2) As String
Dim shoppingList As String
shoppingItem(0) = "Milk"
shoppingItem(1) = "Eggs"
shoppingItem(2) = "Bread"
shoppingList = String.Join(",", shoppingItem)

The value of shoppingList after running this code is "Milk,Eggs,Bread". Note that if your array has empty members, the
method still adds a separator string between all the empty instances in your array.

You can also create an array of strings from a single string by using the String.Split Method. The following example demonstrates
the reverse of the previous example: it takes a shopping list and turns it into an array of shopping items. The separator in this
case is an instance of the Char data type; thus it is appended with the literal type character c.

Copy
Dim shoppingList As String = "Milk,Eggs,Bread"
Dim shoppingItem(2) As String
shoppingItem = shoppingList.Split(","c)

The Visual Basic .NET Mid Function can be used to generate substrings of your string. The following example shows this functions
in use:

Copy
Dim aString As String = "Left Center Right"
Dim rString, lString, mString As String
' rString = "Right"
rString = Mid(aString, 13)
' lString = "Left"
lString = Mid(aString, 1, 4)
' mString = "Center"
mString = Mid(aString, 6,6)

Substrings of your string can also be generated using the String.Substring Method. This method takes two arguments: the
character index where the substring is to start, and the length of the substring. The String.Substring method operates much like
the Mid function. An example is shown below:

Copy
Dim aString As String = "Left Center Right"
Dim subString As String
' subString = "Center"
subString = aString.SubString(5,6)

There is one very important difference between the String.SubString method and the Mid function. The Mid function takes an
argument that indicates the character position for the substring to start, starting with position 1. The String.SubString method
takes an index of the character in the string at which the substring is to start, starting with position 0. Thus, if you have a string
"ABCDE", the individual characters are numbered 1,2,3,4,5 for use with the Mid function, but 0,1,2,3,4 for use with the
System.String function.

DateTime Methods

  Name Description
Add Returns a new DateTime that adds the value of the specified TimeSpan
to the value of this instance.

AddDays Returns a new DateTime that adds the specified number of days to the
value of this instance.

AddHours Returns a new DateTime that adds the specified number of hours to
the value of this instance.

AddMilliseconds Returns a new DateTime that adds the specified number of


milliseconds to the value of this instance.

AddMinutes Returns a new DateTime that adds the specified number of minutes to
the value of this instance.

AddMonths Returns a new DateTime that adds the specified number of months to
the value of this instance.

AddSeconds Returns a new DateTime that adds the specified number of seconds to
the value of this instance.

AddTicks Returns a new DateTime that adds the specified number of ticks to the
value of this instance.

AddYears Returns a new DateTime that adds the specified number of years to the
value of this instance.

Compare Compares two instances of DateTime and returns an integer that


indicates whether the first instance is earlier than, the same as, or later
than the second instance.

CompareTo(DateTime) Compares the value of this instance to a specified DateTime value and
returns an integer that indicates whether this instance is earlier than,
the same as, or later than the specified DateTime value.

CompareTo(Object) Compares the value of this instance to a specified object that contains
a specified DateTime value, and returns an integer that indicates
whether this instance is earlier than, the same as, or later than the
specified DateTime value.

DaysInMonth Returns the number of days in the specified month and year.

Equals(DateTime) Returns a value indicating whether this instance is equal to the


specified DateTime instance.

Equals(Object) Returns a value indicating whether this instance is equal to a specified


object. (Overrides ValueType.Equals(Object).)

Equals(DateTime, DateTime) Returns a value indicating whether two instances of DateTime are
equal.

Finalize Allows an Object to attempt to free resources and perform other


cleanup operations before the Object is reclaimed by garbage
collection. (Inherited from Object.)

FromBinary Deserializes a 64-bit binary value and recreates an original serialized


DateTime object.

FromFileTime Converts the specified Windows file time to an equivalent local time.

FromFileTimeUtc Converts the specified Windows file time to an equivalent UTC time.

FromOADate Returns a DateTime equivalent to the specified OLE Automation Date.

GetDateTimeFormats Converts the value of this instance to all the string representations
supported by the standard date and time format specifiers.

GetDateTimeFormats(Char) Converts the value of this instance to all the string representations
supported by the specified standard date and time format specifier.

GetDateTimeFormats(IFormatProvider) Converts the value of this instance to all the string representations
supported by the standard date and time format specifiers and the
specified culture-specific formatting information.

GetDateTimeFormats(Char, Converts the value of this instance to all the string representations
IFormatProvider) supported by the specified standard date and time format specifier
and culture-specific formatting information.

GetHashCode Returns the hash code for this instance. (Overrides


ValueType.GetHashCode.)

GetType Gets the Type of the current instance. (Inherited from Object.)

GetTypeCode Returns the TypeCode for value type DateTime.

IsDaylightSavingTime Indicates whether this instance of DateTime is within the daylight


saving time range for the current time zone.

IsLeapYear Returns an indication whether the specified year is a leap year.

MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)

Parse(String) Converts the specified string representation of a date and time to its
DateTime equivalent.

Parse(String, IFormatProvider) Converts the specified string representation of a date and time to its
DateTime equivalent using the specified culture-specific format
information.

Parse(String, IFormatProvider, Converts the specified string representation of a date and time to its
DateTimeStyles) DateTime equivalent using the specified culture-specific format
information and formatting style.

ParseExact(String, String, IFormatProvider) Converts the specified string representation of a date and time to its
DateTime equivalent using the specified format and culture-specific
format information. The format of the string representation must
match the specified format exactly.
ParseExact(String, String, IFormatProvider, Converts the specified string representation of a date and time to its
DateTimeStyles) DateTime equivalent using the specified format, culture-specific format
information, and style. The format of the string representation must
match the specified format exactly or an exception is thrown.

ParseExact(String, String(), Converts the specified string representation of a date and time to its
IFormatProvider, DateTimeStyles) DateTime equivalent using the specified array of formats, culture-
specific format information, and style. The format of the string
representation must match at least one of the specified formats exactly
or an exception is thrown.

SpecifyKind Creates a new DateTime object that has the same number of ticks as
the specified DateTime, but is designated as either local time,
Coordinated Universal Time (UTC), or neither, as indicated by the
specified DateTimeKind value.

Subtract(DateTime) Subtracts the specified date and time from this instance.

Subtract(TimeSpan) Subtracts the specified duration from this instance.

ToBinary Serializes the current DateTime object to a 64-bit binary value that
subsequently can be used to recreate the DateTime object.

ToFileTime Converts the value of the current DateTime object to a Windows file
time.

ToFileTimeUtc Converts the value of the current DateTime object to a Windows file
time.

ToLocalTime Converts the value of the current DateTime object to local time.

ToLongDateString Converts the value of the current DateTime object to its equivalent
long date string representation.

ToLongTimeString Converts the value of the current DateTime object to its equivalent
long time string representation.

ToOADate Converts the value of this instance to the equivalent OLE Automation
date.

ToShortDateString Converts the value of the current DateTime object to its equivalent
short date string representation.

ToShortTimeString Converts the value of the current DateTime object to its equivalent
short time string representation.

ToString Converts the value of the current DateTime object to its equivalent
string representation. (Overrides ValueType.ToString.)

ToString(IFormatProvider) Converts the value of the current DateTime object to its equivalent
string representation using the specified culture-specific format
information.
ToString(String) Converts the value of the current DateTime object to its equivalent
string representation using the specified format.

ToString(String, IFormatProvider) Converts the value of the current DateTime object to its equivalent
string representation using the specified format and culture-specific
format information.

ToUniversalTime Converts the value of the current DateTime object to Coordinated


Universal Time (UTC).

TryParse(String, DateTime) Converts the specified string representation of a date and time to its
DateTime equivalent and returns a value that indicates whether the
conversion succeeded.

TryParse(String, IFormatProvider, Converts the specified string representation of a date and time to its
DateTimeStyles, DateTime) DateTime equivalent using the specified culture-specific format
information and formatting style, and returns a value that indicates
whether the conversion succeeded.

TryParseExact(String, String, Converts the specified string representation of a date and time to its
IFormatProvider, DateTimeStyles, DateTime equivalent using the specified format, culture-specific format
DateTime)
information, and style. The format of the string representation must
match the specified format exactly. The method returns a value that
indicates whether the conversion succeeded.

TryParseExact(String, String(), Converts the specified string representation of a date and time to its
IFormatProvider, DateTimeStyles, DateTime equivalent using the specified array of formats, culture-
DateTime)
specific format information, and style. The format of the string
representation must match at least one of the specified formats
exactly. The method returns a value that indicates whether the
conversion succeeded.

You might also like