+ All Categories
Home > Documents > Programming with Visual Basic.NET An Object-Oriented Approach Chapter 8 Introduction to Database...

Programming with Visual Basic.NET An Object-Oriented Approach Chapter 8 Introduction to Database...

Date post: 27-Dec-2015
Category:
Upload: brice-cross
View: 225 times
Download: 1 times
Share this document with a friend
Popular Tags:
42
Programming with Visual Basic .NET An Object-Oriented Approach Chapter 8 Introduction to Database Processing
Transcript

Programming with Visual Basic .NETAn Object-Oriented Approach

Chapter 8

Introduction to Database Processing

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 2

Objectives (1) Understand how VB .NET uses a

database Use ADOc to manage table data Understand the basics of ADO.NET

Define a connection to a database Use a DataAdapter to retrieve data from a

database

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 3

Objectives (2) Use the DataSet class Bind controls to a DataSet Use the ControlBindingsCollection Understand how users navigate between

records Modify a database records Count records

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 4

Introduction to ADO.NET The System.Data namespace provides

access to database data Collectively referred to as ADO.NET

ADO.NET is designed to work well with desktop and Internet applications

Works with different databases Access, SQL Server

Uses a disconnected architecture Note that ADO.NET and ADO are very different

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 5

Establishing a Database Connection ADO.NET Collection class forms a

pipeline between your application and a data source by means of a provider

Two controls supply the connection OleDbConnection control works with

many databases SQLConnection control works only with

SQL server Faster access

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 6

OleDBConnection Class (Introduction) Belongs to the System.Drawing.OleDB

namespace When creating an instance of the

OleDbConnection control, VB .NET writes code to create an instance of the OleDbConnection class and configure it

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 7

OleDbConnection Class(Properties) Properties

ConnectionString property contains a string defining the database provider, database name, and security information

ConnectionTimeout property defines the number of seconds to wait for a connection to be established

DataSource property gets location and file name of the database

Provider property specifies property that will be used to establish the database connection

State property defines connection status (open, closed, etc.)

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 8

OleDbConnection Class(Methods and Events) Methods

Close method closes an open connection Open method opens a closed connection

Uses the contents of ConnectionString property to open the connection

Events StateChanged event fires when the

connection state (State property) changes

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 9

Connection (Illustration)

Your solutionYour

solutionADO.NET connectio

n

ADO.NET connectio

n

Database provider

Database provider

databasedatabaseSends command

sGets data

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 10

Creating a Connection (Step 1)

Select Microsoft Jet 4.0 OLE DB Provider for Access databases

Select Microsoft Jet 4.0 OLE DB Provider for Access databases

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 11

Creating a Connection (Step 2)

Select databaseSelect database

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 12

Code Behind a Database Connection Provider key specifies the database

provider User ID and Password keys supply

authentication information Data Source key supplies database file Mode key defines how database will be

shared among connected usersProvider=Microsoft.Jet.OLEDB.4.0;Password="";User ID=Admin;Data Source=D:\VBOOP7\Chapter.08\Data\Employees.mdb;Mode=Share Deny None . . .

Provider=Microsoft.Jet.OLEDB.4.0;Password="";User ID=Admin;Data Source=D:\VBOOP7\Chapter.08\Data\Employees.mdb;Mode=Share Deny None . . .

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 13

The DataAdapter Use the OleDBDataAdapter control to

create a DataAdapter Control supports a Wizard to help you

configure the DataAdapter Wizard writes code to create an instance

of the OleDbDataAdapter class Wizard writes SQL statements to select,

update, and delete records

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 14

The DataAdapter Class Properties

SelectCommand property contains an SQL SELECT statement

InsertCommand, UpdateCommand, and DeleteCommand properties contain SQL INSERT, UPDATE, and DELETE statements

Methods Fill method uses a connection to fill a DataSet

with data Update method sends changed data back to the

DataSet

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 15

Creating a Data Adapter (Step 1) Create an instance of the

OleDbDataAdapter control on the form VB .NET activates the Wizard

Wizard starts by displaying an introductory screen

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 16

Creating a Data Adapter (Step 2) Add tables to the database

Select table(s) to useSelect table(s) to use

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 17

Creating a Data Adapter (Step 3) Define the SQL

statementSelect columnsSelect columns

Sort columnsSort columns

SELECT statementSELECT statement

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 18

Creating a Data Adapter (Step 4)

Completed SQL SELECT statement

Completed SQL SELECT statement

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 19

The Role of the DataSet The DataAdapter retrieves rows into

another object called a DataSet DataSet is NOT connected to the database

once the data has been retrieved DataSet contains one or more tables

Each table in the DataSet contains one or more rows

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 20

The Role of the DataSet (Illustration)

Your solutionYour

solution

ProviderProviderConnection

Connection databasedatabase

DataSet

DataAdapter sends

command

DataAdapter sends

command

DataAdapter creates DataSet

DataAdapter creates DataSet

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 21

Creating a DataSet

Enter DataSet nameEnter DataSet name

Select tableSelect table

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 22

The DataSet Class The Tables property gets a list of tables stored in

the DataSet For each table VB .NET defines a property having the

same name as the underlying table Clear method removes all the data from the DataSet

DataSet is not connected so data is not removed from the database

AcceptChanges marks any changed rows as unchanged Use to synchronize the DataSet with the database Automatically called after an Update

GetChanges method gets rows containing changed records

HasChanges method determines if there are changed records

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 23

The DataTable Class Columns property returns a collection of columns

Use for schema information DataSet property returns a reference to the

parent DataSet object Rows property returns the collection of rows in

the DataTable Use for data

TableName property contains a string defining the table name

AcceptChanges, Clear, and NewRow methods are the same as the properties of the DataSet itself

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 24

Filling a Dataset Call the Fill method of the DataAdapter

using the DataSet name as the argument Assume that the DataAdapter is named

odbdaEmployees and the DataSet is named DsEmployees1 Note pintRecords contains the number of

records returnedDim pintRecords As Integer

pintRecords = odbdaEmployees.Fill(DsEmployees1)

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 25

DataBinding Users typically want to see data appearing

in a text box or other control instance The process of associating a control

instance like a text box with a field in a data source is called data binding

Two types of data binding Simple binding – Display 1 row from a data

source Complex binding – Display multiple rows

from a data source

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 26

The Binding Object Create a Binding object so as to bind a control

instance to a data source Note that the Binding object specifies the control

property to bind, not the control instance to bind Syntax:

Binding constructor

Public Sub New( ByVal propertyname As string, ByVal datasource As Object, ByVal datamember As String) As String

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 27

Binding Constructor (Arguments) propertyname contains the name of the

control property to bind The Text property of a TextBox for

example datasource contains the name of a

DataSet or DataTable object datamember provides the navigation

path to a field in the DataSet

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 28

Binding Constructor (Example)

Create a new binding Text property DataSet named DsEmployees1 Navigation Path is

"tblEmployees.fldEmployeeID"

Dim pbndTemp As Binding

pbndTemp = New Binding("Text, _

DsEmployees1, _

"tblEmployees.fldEmployeeID")

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 29

The ControlBindingsCollection Using with an instance of the Binding class to

bind a control Call the Add method to bind the control

instance Call the Clear method to remove all the

bindings Count property gets the number of elements

in the collection Item property gets a specific binding from the

collection

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 30

Adding a Control Binding Add method syntax:Overloads Public Function Add

( ByVal binding As Binding ) As Binding Binding argument contains the name of an

existing binding Method returns the binding that was

added

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 31

Adding a Control Binding (Example) Create a binding and add associate it

with the text box named txtEmployeeID

Dim pbndTemp As BindingpbndTemp = New Binding("Text", DsEmployees1, _ "tblEmployees.fldEmployeeID")txtEmployeeID.DataBindings.Add(pbndTemp)txtEmployeeID.DataBindings.Add("Text", DsEmployees1, _ "tblEmployees.fldEmployeeID")

Dim pbndTemp As BindingpbndTemp = New Binding("Text", DsEmployees1, _ "tblEmployees.fldEmployeeID")txtEmployeeID.DataBindings.Add(pbndTemp)txtEmployeeID.DataBindings.Add("Text", DsEmployees1, _ "tblEmployees.fldEmployeeID")

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 32

Record Navigation (Overview) Users need a way to navigate from

record to record Use the BindingContext of the Form

class Multiple BindingContexts can exists

CurrencyManager and BindingContext keep control instances synchronized

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 33

BindingManageBase Use with the BindingContext

Set the Position property to navigate Count property gets the number of

managed rows AddNew method adds a new item EndCurrentEdit method ends the editing

process RemoveAt method removes a row

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 34

Record Navigation (First Record) Set the Position property of the Binding

Context to 0 to locate the first row Note Position property is 0-based Me keyword references the form

Me.BindingContext(DsEmployees1, _ "tblEmployees").Position = 0

Me.BindingContext(DsEmployees1, _ "tblEmployees").Position = 0

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 35

Record Navigation (Previous Record) Decrement the Position property of the

BindingContext by 1 to locate the previous record

Me.BindingContext(DsEmployees1, "tblEmployees").Position -= 1

Me.BindingContext(DsEmployees1, "tblEmployees").Position -= 1

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 36

Record Navigation (Next Record) Increment the Position property of the

BindingContext by 1 to locate the next recordMe.BindingContext(DsEmployees1, "tblEmployees").Position += 1

Me.BindingContext(DsEmployees1, "tblEmployees").Position += 1

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 37

Record Navigation (Last Record) Use the underlying DataSet and

DataTable to determine the row count

Me.BindingContext(DsEmployees1, _ "tblEmployees").Position = _ Me.DsEmployees1.tblEmployees.Rows.Count - 1

Me.BindingContext(DsEmployees1, _ "tblEmployees").Position = _ Me.DsEmployees1.tblEmployees.Rows.Count - 1

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 38

Adding Records When adding a record, the new record

(stored in the DataSet) must be saved to the database First get the newly added row from the

database Using the DataAdapter, call the Update

method to save the changes to the database Call the AcceptChanges method on the

DataSet to synchronize the DataSet and database

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 39

Adding Records (Example) End editing, update the database, and

then call AcceptChangesMe.BindingContext(DsEmployees1, _ "tblEmployees").EndCurrentEditpdsInsertedRows = _ DsEmployees1.GetChanges(DataRowState.Added) If Not pdsInsertedRows Is Nothing Then odbdaEmployees.Update(pdsInsertedRows)End If

DsEmployees1.AcceptChanges

Me.BindingContext(DsEmployees1, _ "tblEmployees").EndCurrentEditpdsInsertedRows = _ DsEmployees1.GetChanges(DataRowState.Added) If Not pdsInsertedRows Is Nothing Then odbdaEmployees.Update(pdsInsertedRows)End If

DsEmployees1.AcceptChanges

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 40

Deleting Records Call the RemoveAt method of the

BindingContext Call the GetChanges method on the

DataSet to get the removed record Call the Update method on the

DataAdapter to save the changes Call the AcceptChanges method on

the DataSet to synchronize the DataSet and database

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 41

Deleting Records (Example)

Dim pdsDeletedRows As DataSet

Me.BindingContext(DsEmployees1, "tblEmployees"). _ RemoveAt(Me.BindingContext(DsEmployees1, _ "tblEmployees").Position)

pdsDeletedRows = _ DsEmployees1.GetChanges(DataRowState.Deleted)

odbdaEmployees.Update(pdsDeletedRows)DsEmployees1.AcceptChanges()

Dim pdsDeletedRows As DataSet

Me.BindingContext(DsEmployees1, "tblEmployees"). _ RemoveAt(Me.BindingContext(DsEmployees1, _ "tblEmployees").Position)

pdsDeletedRows = _ DsEmployees1.GetChanges(DataRowState.Deleted)

odbdaEmployees.Update(pdsDeletedRows)DsEmployees1.AcceptChanges()

Programming with Visual Basic .NETAn Object-Oriented ApproachSlide 42

Canceling an Update Call the CancelCurrentEdit method on

the BindingContext

Me.BindingContext(DsEmployees1, _ "tblEmployees").CancelCurrentEdit

Me.BindingContext(DsEmployees1, _ "tblEmployees").CancelCurrentEdit


Recommended