You are on page 1of 12

qwertyuiopasdfghjklzxcvbnmqwertyui

opasdfghjklzxcvbnmqwertyuiopasdfgh
jklzxcvbnmqwertyuiopasdfghjklzxcvb
nmqwertyuiopasdfghjklzxcvbnmqwer
tyuiopasdfghjklzxcvbnmqwertyuiopas
dfghjklzxcvbnmqwertyuiopasdfghjklzx
Database programming with
Visual Basic .Net
cvbnmqwertyuiopasdfghjklzxcvbnmq
ADO .NET
Nadeera Ahangama

wertyuiopasdfghjklzxcvbnmqwertyuio
Asia Pacific Institute of Information Technology – A. P. I . I . T

pasdfghjklzxcvbnmqwertyuiopasdfghj
klzxcvbnmqwertyuiopasdfghjklzxcvbn
mqwertyuiopasdfghjklzxcvbnmqwerty
uiopasdfghjklzxcvbnmqwertyuiopasdf
ghjklzxcvbnmqwertyuiopasdfghjklzxc
vbnmqwertyuiopasdfghjklzxcvbnmrty
uiopasdfghjklzxcvbnmqwertyuiopasdf
ghjklzxcvbnmqwertyuiopasdfghjklzxc
Database programming with Visual Basic .Net 2

Introduction to databases
Databases form an essential part of almost all enterprises today. Over the last four decades of the
twentieth century, use of databases grew in all enterprises. Some representative applications of
databases shall be listed as follows.

Banking – to store and keep track of information such as customer, account, loans, transactions,
teller etc.
Airlines – for reservations and schedule information
Universities – for student information, course registration, time tabling etc
Telecommunication companies – for records of calls and services, billing, prepaid account
information etc.

Database Management systems (DBMS)


Technically speaking, it is a software system that uses a standard method of cataloging, retrieving, and
running queries on data. The DBMS manages incoming data, organizes it, and provides ways for the data
to be modified or extracted by users or other programs.

Some DBMS examples include Microsoft Access , Microsift SQL Server, MySQL, PostgreSQL, Oracle,
dBASE, DB2, and FoxPro. Since there are so many database management systems available, it is
important for there to be a way for them to communicate with each other. For this reason, most
database software comes with an Open Database Connectivity (ODBC) driver that allows the database to
integrate with other databases. For example, common SQL statements such as SELECT and INSERT are
translated from a program's proprietary syntax into a syntax other databases can understand.

Advantages of using database systems


The older way to keep information on a computer is to store it in operating system files i.e. file based
systems. File based systems store permanent records in various files and they require different
application programs. Keeping organizational information in a file processing system has number of
major disadvantages.

Following is a list of advantages of using a database system:

Avoid data redundancy/duplication


Avoid inconsistencies (various versions of same data)
Easy to access data, filter and query
Maintains integrity constraints of data
Provide concurrent access
Offer high data security

VBDN – AAPP008-3-2
A.P.I.I.T
Database programming with Visual Basic .Net 3

Database Programming
In the modern world, business applications need to manage voluminous data. Data is normally stored in
a relational database in the form of related tables. Functionality of a database may be quite complex to
understand by a non computer person. Most business applications allow users to retrieve the data
stored in a database and present it in a user-friendly interface without having to write database
commands. The user can add, delete and update records directly from applications. User interfaces hide
complexities of databases offering simple graphical environment.

Here we discuss the concept of connecting a database with a graphical user interface application.

Backend (Ex: Oracle, SQL Server, MS Access …) Front-End (Ex: Vb.Net, Java, C#...)

ADO .NET
Database management systems provide APIs that allow application programmers to create and access
databases. The set of APIs that each manufacturer's system supplies is unique to that manufacturer.
Microsoft's previous steps in this direction included Open Database Connectivity (ODBC), OLE DB, and
ADO (not to be confused with ADO.NET). Microsoft has made improvements with each new technology.

With .NET, Microsoft has released a new mechanism for accessing data: ADO.NET. The name is a
carryover from Microsoft's ADO (ActiveX Data Objects) technology. ADO.NET is not a descendant of
early ADO, it's a new technology. In order to support the Internet evolution, ADO.NET is highly focused
on disconnected data and on the ability for anything to be a source of data.

When speaking of data access, it's useful to distinguish between providers of data and consumers of
data. A data provider encapsulates data and provides access to it in a generic way. The data itself can be
in any form or location. For example, the data may be in a typical database management system such as
SQL Server, or it may be distributed around the world and accessed via web services. The data provider
shields the data consumer from having to know how to reach the data. In ADO.NET, data providers are
referred to as managed providers.

VBDN – AAPP008-3-2
A.P.I.I.T
Database programming with Visual Basic .Net 4

Features of ADO .NET


ADO .NET is a model used by .NET applications, to communicate with a database for retrieving,
accessing, and updating data. Following shall be highlighted as main features of ADO .Net.

Disconnected data architecture


▪ ADO.NET uses the disconnected data architecture
▪ Applications connect to the database only while retrieving and updating data
▪ After the data is retrieved, the connection with the database is closed
▪ When the database needs to be updated, the connection is re-established
▪ This disconnected nature preserves valuable system resources
▪ In a disconnected architecture, a database can cater to the needs of several applications
simultaneously
Data cashed in datasets
▪ A dataset is the most common method of a accessing data in ADO .NET since it
implements a disconnected architecture
▪ Since ADO .NET is based on a disconnected data structure, it is not possible for the
application to interact with the database for processing each record. Therefore, the data
is retrieved and stored in datasets
▪ A dataset is a cashed set of database records
▪ You can work with datasets in the same way you do with real data, the only difference is
that dataset is independent of data source and you remain disconnected from the data
source. As a result, resources are saved, and the database can meet the increasing
demands of users
Data transfer in XML format
▪ XML is the fundamental format of data transfer in ADO .NET.
▪ XML is an industry standard format for exchanging information between different types
of applications
▪ Data is transferred from a database into a dataset & from dataset to a another
component by using XML
▪ You can even use an XML file as a data source and store data from it in a dataset
▪ The knowledge of XML is not required for working ADO .NET since data conversion from
and to XML is hidden from the user

Interaction with database is done through data commands


▪ A DataCommand object can be used for accessing or updating the data using SQL
statements

VBDN – AAPP008-3-2
A.P.I.I.T
Database programming with Visual Basic .Net 5

ADO .NET Framework

ADO .NET Framework

Data Provider
Despite the disconnected model of programming you still need to connect to the physical database
actually to retrieve, update, insert or delete data from a database. The software that communicates with
the physical database in ADO .Net is called a data provider.

The .NET data provider is the layer between the application and the database that takes care of the all
functionalities of database interaction. They are designed for fast, efficient means of data retrieval and
reconciliation. The following table lists the .NET Framework data providers that are included in the .NET
Framework.

.NET Framework data provider Description

.NET Framework Data Provider for SQL For Microsoft® SQL Server™ version 7.0 or later.
Server

.NET Framework Data Provider for OLE For data sources exposed using OLE DB. Such as Jet OLE DB
DB provider for Microsoft Access.

.NET Framework Data Provider for For data sources exposed using ODBC.
ODBC

.NET Framework Data Provider for For Oracle data sources. The .NET Framework Data Provider for
Oracle Oracle supports Oracle client software version 8.1.7 and later.

VBDN – AAPP008-3-2
A.P.I.I.T
Database programming with Visual Basic .Net 6

Connection Object
A connection object is simply a representation of an open connection to a data source. Connection
object is merely the pipe line that commands and queries use to send their SQL statements and receive
results.

Connection objects typically can be thought as the place where you set the connection string.
Essentially, connection objects provide a medium for sending commands to a database and retrieving
data and information into your application.

Commands and Queries

Connection object
Database

Commands and Queries

Figure: Connection objects are your application’s communication pipeline to a database

Creating connection objects programmatically


The first step is to decide which type of connection object to create. The choice is fairly simple because
it is dependent on the back-end data source your application needs to communicate with. Following
table lists the primary connection objects available in ADO .NET and the data sources they designed to
access.

Name Target Data Source

SqlConnection SQL Server 2000 and SQL Server 2005


databases
OleDbConnection OLE DB data sources such as Office access
databases via Jet 4.0
OdbcConnection Open database connectivity(ODBC) data
sources such as a Data Source Name(DSN)
OracleConnection Oracle 7.3, 8i, or 9i databases

VBDN – AAPP008-3-2
A.P.I.I.T
Database programming with Visual Basic .Net 7

Properties and methods of Connection object


ConnectionString Gets or sets the string used to open the connection

It provides information, such as the data source and database name,


that is used to establish connection with database

Open() It is used to open a connection with the data source that is specified in
the ConnectionString property
Close() It is used to close the connection with a date source
State Used to describe the current status of the connection object
Value 0 indicates that the connection is closed
Value 1 indicates that the connection is open

Configuring Connections and connecting to data


Microsoft SQL Server Express
Microsoft SQL Server Express is the freely-downloadable and distributable version of Microsoft's SQL
Server relational database management system. It offers a database solution specifically targeted for
embedded and smaller-scale applications. SQL Server 2005 Express Edition is the next version of MSDE
and is a free, easy-to-use, lightweight, and embeddable version of SQL Server 2005. Microsoft SQL
Server Express comes embedded to Microsoft visual Studio 2005.

Creating SQL Express Database


1. Select Server Explorer from View Menu

2. Right click Data Connections then choose Create new SQL Database…

VBDN – AAPP008-3-2
A.P.I.I.T
Database programming with Visual Basic .Net 8

3. Enter your server name and enter a name for database that you wish to create.

4. Now a database is created by the name FoodWorldDB.

5. Now in order to add a table to the database, Right click Tables folder and choose Add New
Table

6. Add fields and appropriate data types to the table design. Set appropriate keys.

VBDN – AAPP008-3-2
A.P.I.I.T
Database programming with Visual Basic .Net 9

7. Save the table structure by giving an appropriate name for the table (CTRL + S).

8. Data shall be entered to table by right clicking the table name in the server explorer and
choosing Show Table Data.

9. Insert row-wise data to the table.

Creating SQL Server Connection Objects in Code


Create SqlConnection objects with the New keyword. You can instantiate the connection and set the
connection and set the connection string in the same call, or you assign the connection string to the
SqlConnection.ConnectionString property after instantiating the connection. Be sure to replace
ServerName and DatabaseName with valid values for your environment.

VBDN – AAPP008-3-2
A.P.I.I.T
Database programming with Visual Basic .Net 10

Make sure to specify Imports.System.Data.SqlClient in the top of your code to eliminate the need to
qualify the objects fully in code.

Imports.System.Data.SqlClient

Dim connectionObject As New SqlConnection(“Data Source=ServerName; Initial Catalog=Database Name;


Integrated Security=True”)

Opening and Closing Data Connections


Open and close connections using the appropriately named Open and Close methods. To open a
connection to a database, the connection object must contain a connection string that points to a valid
data source.
ConnectionObject.Open( )

ConnectionObject.Close( )

How to run a command


Commands are issued against databases to take actions against data stores and to include any
statement that can be issued against a database. You can use SqlCommand classes to get a command to
your data store.

With ADO, you can issue commands through the Command or the Connection object.

Create a SqlCommand object and pass in the command that you want to run and the connection object
that you created in the previous step. The following sample code passes in the INSERT statement:

Dim sSQL As String = "INSERT INTO Employee " & _


"(emp_id, fname, minit, lname, job_id, job_lvl, pub_id, hire_date)" & _
"VALUES ('MSD12923F', 'Duncan', 'W', 'Mackenzie', 10, 82,'0877','2001-01-01')"
Dim objCmd As New SqlCommand(sSQL, objConn)

After you create the SqlCommand object, you can call the ExecuteNonQuery method to run the
command that it represents. ExecuteNonQuery is designed for commands that do not return any results
(such as the DELETE, the UPDATE, and the INSERT statements). If the Execute statement runs without
throwing an exception (see the following code), the command has been executed successfully against
the database.

objCmd.ExecuteNonQuery()

VBDN – AAPP008-3-2
A.P.I.I.T
Database programming with Visual Basic .Net 11

What is a DataAdapter?
A data adapter is the component that exists between the local repository (dataset) and the physical
database. It contains the four different commands (SELECT, INSERT, UPDATE and DELETE). It uses these
commands to fetch the data from the database and fill into the dataset and to perform updates done in
the dataset to the physical database. It is the data adapter that is responsible for opening and closing
the database connection and communicates with the dataset.

How to Create DataAdapter Objects


You can create a data adapter object programmatically by instantiating an instance of the desired
provider specific adapter and passing in a SELECT statement and a valid Connection Object to the
constructor.

The following code shows how to instantiate a new Data Adapter by passing the initial SELECT statement
and a valid connection object to the constructor.

Dim SqlDataAdapterName as New SqlDataAdapter(“Sql Statement”, ConnectionObject)

DataAdapter Commands
When creating DataAdapter programmatically, you may want to create commands manually, or when
using complex queries you may need to manually configure commands used for updating. There are two
ways to configure commands for a DataAdapter: you can create Command Objects and assign them to
their corresponding DataAdapter properties, or you can use a CommandBuilder object.

DataSet
The DataSet, which is an in-memory cache of data retrieved from a data source, is a major component
of the ADO.NET architecture. The DataSet consists of a collection of DataTable objects that you can
relate to each other with DataRelation objects.

VBDN – AAPP008-3-2
A.P.I.I.T
Database programming with Visual Basic .Net 12

A DataSet can be used for manipulating the data remotely and finally updating the database with the
modified data. This way it enables disconnected means of working with data. This improves
performance in terms of reducing the number of times a database is accessed for data manipulations.

The dataset contains all the objects as a Collection of objects. For example it contains the Database
Tables as DataTable objects. The data from the database is filled into the dataset by using the
DataAdapter.

How to create a DataSet in code


ConnectionObject.Open()

Dim DataSetName As New DataSet

Dim DataAdapterName As SqlDataAdapter

DataAdapterName = New SqlDataAdapter("Select * from Table1", ConnectionObject)

DataAdapterName.Fill(DataSetName, "DatasetTableName")

VBDN – AAPP008-3-2
A.P.I.I.T

You might also like