77
Visual Basic.NET Programming ADO Programming February 11, 2004

Visual Basic.NET Programming ADO Programming February 11, 2004

Embed Size (px)

Citation preview

Page 1: Visual Basic.NET Programming ADO Programming February 11, 2004

Visual Basic.NET ProgrammingADO ProgrammingFebruary 11, 2004

Page 2: Visual Basic.NET Programming ADO Programming February 11, 2004

AgendaQuestions / Homework

Namespaces

Files, Streams and Directories

OpenFileDialog and SaveFileDialog

Class Exercise FileIO Class

Databases

ADO.NET

Grid Control

Class Exercise

Homework

Page 3: Visual Basic.NET Programming ADO Programming February 11, 2004

Coming Attractions

•February 18, 2004 – ASP.NET Programming– Web Forms– ASP.NET Controls

•February 18, 2004– Web Services

•March 3, 2004– More Web Services

Page 4: Visual Basic.NET Programming ADO Programming February 11, 2004

Open Questions

• Open Homework Assignments

• Visual Studio Class Library Root Namespace Namespaces and a Demo

• Collections and Serialization / Deserialization Class Demo

Page 5: Visual Basic.NET Programming ADO Programming February 11, 2004

Namespaces

Page 6: Visual Basic.NET Programming ADO Programming February 11, 2004

Namespaces

• The Namespace keyword is used to declare a scope. This namespace scope lets you organize code and gives you a way to create globally-unique types.

• Even if you do not explicitly declare one, a default namespace is created. This unnamed namespace, sometimes called the global namespace, is present in every file. Any identifier in the global namespace is available for use in a named namespace.

• Namespaces implicitly have public access and this is not modifiable.

Page 7: Visual Basic.NET Programming ADO Programming February 11, 2004

Namespaces• Used to organize classes and types into a

hierarchical structure.• Makes it easier to find types.• Helps prevent name collisions.• Declared with the Namespace keyword.

Namespace HelloVS

End Namespace

Namespaces can be nestedNamespace HelloVS Namespace HelloVS.Foo

Page 8: Visual Basic.NET Programming ADO Programming February 11, 2004

NamespacesNamespace name[.name1] ...]

name, name1 - A Namespace name can be any legal identifier. ANamespace name can contain periods.

type-declarations - Within a Namespace, you can declare one or more of the following types:

• another Nnamespace

• Class

• Interface

• Struct

• Enum

• Delegate

Page 9: Visual Basic.NET Programming ADO Programming February 11, 2004

Namespaces and Imports• Namespaces can get pretty long

– e.g. System.Runtime.Remoting.Channels.HttpChannel– To use the HttpChannel class, you would need to type:

System.Runtime.Remoting.Channels.Http.HttpChannel• Fortunately, with a Namespace rather than... Dim hc As System.Runtime.Remoting.Channels.HttpChannel

you can use...Imports System.Runtime.Remoting.Channels.HttpDim hc As HttpChannel

• Imports is just syntactic sugar, does not link any code automatically.

• So System.Console.WriteLine can become Console.WriteLine

Page 10: Visual Basic.NET Programming ADO Programming February 11, 2004

Class Library Namespace

• Click on Project Properties

• Root namespace is under common properties

Page 11: Visual Basic.NET Programming ADO Programming February 11, 2004
Page 12: Visual Basic.NET Programming ADO Programming February 11, 2004

Files, Streams and Directories

Page 13: Visual Basic.NET Programming ADO Programming February 11, 2004

Files, Streams and Directories

• Directories and Files• Reading and Writing a Sequential Files • Using OpenFileDialog and SaveFileDialog

Page 14: Visual Basic.NET Programming ADO Programming February 11, 2004

System.IO Namespace

• Directory Class • File Class • StreamReader Class • SteamWriter Class

Page 15: Visual Basic.NET Programming ADO Programming February 11, 2004

System.IO Namespace• Directory Class - Exposes static methods for creating,

moving, and enumerating through directories and subdirectories.

• File Class - Provides static methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects.

• StreamReader Class - Implements a TextReader that reads characters from a byte stream in a particular encoding.

• SteamWriter Class - Implements a TextWriter for writing characters to a stream in a particular encoding.

Page 16: Visual Basic.NET Programming ADO Programming February 11, 2004

Directory Class

Exposes static methods for creating, moving, and enumerating through directories and subdirectories.

Page 17: Visual Basic.NET Programming ADO Programming February 11, 2004

Directory ClassImports System.IOPublic Class Test

Public Shared Sub Main()Dim path As String = "c:\MyDir"Dim target As String = "c:\TestDir"Try If Directory.Exists(path) = False Then

Directory.CreateDirectory(path) Create Dir. End If If Directory.Exists(target) Then

Directory.Delete(target, True) Delete Directory End If Directory.Move(path, target) Move Directory File.CreateText(target + "\myfile.txt") New File

Catch Ex As Exception Console.WriteLine(Ex.message)

End TryEnd Sub

End Class

Page 18: Visual Basic.NET Programming ADO Programming February 11, 2004

File Class

Provides static methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of

FileStream objects.

Page 19: Visual Basic.NET Programming ADO Programming February 11, 2004

File Class

Imports System.IOPublic Class Test

Public Shared Sub Main()Dim target As String = "c:\TestDir\Test.Txt"

If File.Exists(target ) Then File.Delete(target ) End If

If File.Exists(target ) = False Then Dim sw As StreamWriter = File.CreateText(target)

sw.WriteLine("Hello World") sw.Close() End If

End SubEnd Class

Page 20: Visual Basic.NET Programming ADO Programming February 11, 2004

StreamReader Class

Implements a TextReader that reads characters from a byte stream in a particular encoding.

Page 21: Visual Basic.NET Programming ADO Programming February 11, 2004

StreamReader ClassImports SystemImports System.IOClass Test Public Shared Sub Main() Try Dim sr As StreamReader = New StreamReader("TestFile.txt") Dim line As String Do line = sr.ReadLine() Console.WriteLine(Line) Loop Until line Is Nothing sr.Close() Catch E As Exception Console.WriteLine("The file could not be read:") Console.WriteLine(E.Message) End Try End SubEnd Class

Page 22: Visual Basic.NET Programming ADO Programming February 11, 2004

SteamWriter Class

Implements a TextWriter for writing characters to a stream in a particular encoding.

Page 23: Visual Basic.NET Programming ADO Programming February 11, 2004

StreamWriter Class

Imports SystemImports System.IOClass Test Public Shared Sub Main() Dim sw As StreamWriter = New StreamWriter("TestFile.txt") sw.Write("This is the ") sw.WriteLine("header for the file.") sw.WriteLine("-------------------") sw.Write("The date is: ") sw.WriteLine(DateTime.Now) sw.Close() End SubEnd Class

Page 24: Visual Basic.NET Programming ADO Programming February 11, 2004
Page 25: Visual Basic.NET Programming ADO Programming February 11, 2004

OpenFileDialogand

SaveFileDialog

Page 26: Visual Basic.NET Programming ADO Programming February 11, 2004

OpenFileDialog Class

• Represents a common dialog box that displays the control that allows the user to open a file.

• This class allows you to check whether a file exists and to open it. The ShowReadOnly property determines whether a read-only check box appears in the dialog box.

• The ReadOnlyChecked property indicates whether the read-only check box is checked.

• Imports requires (default with Forms application)

System.Windows.Forms

Page 27: Visual Basic.NET Programming ADO Programming February 11, 2004
Page 28: Visual Basic.NET Programming ADO Programming February 11, 2004

OpenFileDialogProtected Sub button1_Click(sender As Object, e As System.EventArgs) Dim myStream As Stream Dim openFileDialog1 As New OpenFileDialog() openFileDialog1.InitialDirectory = "c:\" openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" openFileDialog1.FilterIndex = 2 openFileDialog1.RestoreDirectory = True If openFileDialog1.ShowDialog() = DialogResult.OK Then myStream = openFileDialog1.OpenFile() If Not (myStream Is Nothing) Then ' Insert code to read the stream here. myStream.Close() End If End IfEnd Sub

Page 29: Visual Basic.NET Programming ADO Programming February 11, 2004

SaveFileDialog Class

• Represents a common dialog box that allows the user to specify options for saving a file.

• Imports requires (default with Forms application)

System.Windows.Forms

• This class allows you to open and overwrite an existing file or create a new file.

Page 30: Visual Basic.NET Programming ADO Programming February 11, 2004
Page 31: Visual Basic.NET Programming ADO Programming February 11, 2004

SaveFileDialogProtected Sub button1_Click(sender As Object, e As System.EventArgs) Dim myStream As Stream Dim saveFileDialog1 As New SaveFileDialog() saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" saveFileDialog1.FilterIndex = 2 saveFileDialog1.RestoreDirectory = True If saveFileDialog1.ShowDialog() = DialogResult.OK Then myStream = saveFileDialog1.OpenFile() If Not (myStream Is Nothing) Then ' Code to write the stream goes here. myStream.Close() End If End IfEnd Sub

Page 32: Visual Basic.NET Programming ADO Programming February 11, 2004
Page 33: Visual Basic.NET Programming ADO Programming February 11, 2004

Class Exercise FileIO Class

Page 34: Visual Basic.NET Programming ADO Programming February 11, 2004

File and Directory Class Exercise

• Modify the NameAddress application as follows, before you write a serialized file:– Test for a specific directory, if it exists delete it– Create the same directory– Use the SaveFileDialog to select the target file name

and directory for saving the serialize file.• Before you read the serialized file use the

OpenFileDialog to select the deseriale file.

Page 35: Visual Basic.NET Programming ADO Programming February 11, 2004
Page 36: Visual Basic.NET Programming ADO Programming February 11, 2004

Databases

Page 37: Visual Basic.NET Programming ADO Programming February 11, 2004

Databases and SQL

Introduction

Relational Database Model

Structured Query Language (SQL)Basic: SELECT Query

WHERE ClauseORDER BY ClauseINSERT Statement

  UPDATE StatementDELETE Statement

Page 38: Visual Basic.NET Programming ADO Programming February 11, 2004

Introduction

Database:– Integrated collection of data– Database management system (DBMS)

• Provides mechanisms for storing and organizing data in a way that is consistent with database’s format

• Allows storage and access to database without knowledge of internal representation

– Relational Databases most popular• Use Structured Query Language to perform queries

(search) and manipulate data• Programming languages need an interface to interact with

relational databases

Page 39: Visual Basic.NET Programming ADO Programming February 11, 2004

Relational Database Model

• Logical representation of data:– Relationships can be considered without

concern for physical structure of data

• Composed of tables– Rows called records– Columns called fields– Primary key: field that contains unique data

• Each record can be identified by at least one distinct value

– New sets made from queries called result sets

Page 40: Visual Basic.NET Programming ADO Programming February 11, 2004

Relational Database Modelnumber name department salary location

23603 Jones 413 1100 New Jersey

24568 Kerwin 413 2000 New Jersey

34589 Larson 642 1800 Los Angeles

35761 Myers 611 1400 Orlando

47132 Neumann 413 9000 New Jersey

78321 Stephens 611 8500 Orlando

record/row

field/columnprimary key

Page 41: Visual Basic.NET Programming ADO Programming February 11, 2004

Structured Query Language (SQL)

• Used to request data (perform queries) and manipulate data

Page 42: Visual Basic.NET Programming ADO Programming February 11, 2004

Structured Query Language (SQL)

SQL Key Word Description

SELECT Select (retrieve) fields from one or more tables.

FROM Tables from which to get fields. Required in every Select statement.

WHERE Criteria for selection that determines the rows to be retrieved.

ORDER BY Criteria for ordering records.

Page 43: Visual Basic.NET Programming ADO Programming February 11, 2004

Basic Select Query• Extracts information from one or more tables in a

database• Format:

– Basic: SELECT * FROM tableName– * extracts all columns– To get specific fields use a comma separated

list instead of *• Example:

SELECT * FROM Books

Page 44: Visual Basic.NET Programming ADO Programming February 11, 2004

Where Clause• Used to specify certain criteria in a query• Basic form:

– SELECT * FROM tableName WHERE criteria• Example:

– SELECT * FROM Books WHERE Author = ‘Robert Parker’

• Can use LIKE clause– Used for pattern matching

• Uses wildcards– *: zero or more characters take its place– ?: exactly one character takes its place

Page 45: Visual Basic.NET Programming ADO Programming February 11, 2004

ORDER BY Clause• Used to arrange results of a query

– Can be ascending or descending order• Uses ASC and DESC respectively

• Example:

SELECT * FROM Books ORDER BY Copyright DSC

• Can be used to sort by multiple fields

Page 46: Visual Basic.NET Programming ADO Programming February 11, 2004

Insert Statement

• Inserts a new record into a table• Form:

INSERT INTO tableName(fieldName1, …) VALUES (value1, …)

• Values must match field names in order and type

Page 47: Visual Basic.NET Programming ADO Programming February 11, 2004

UPDATE Statement

• Modifies data in a table• Form:

UPDATE tableName SET fieldName1 = value1 WHERE criteria

Page 48: Visual Basic.NET Programming ADO Programming February 11, 2004

DELETE Statement

• Removes data from a table• Form:

DELETE FROM tableName WHERE criteria

Page 49: Visual Basic.NET Programming ADO Programming February 11, 2004
Page 50: Visual Basic.NET Programming ADO Programming February 11, 2004

ADO.NET

Page 51: Visual Basic.NET Programming ADO Programming February 11, 2004

ADO Components

• DataAdapter

• DBConnection and DBCommand

• Datasets

• Grid Control

• XML Output

Page 52: Visual Basic.NET Programming ADO Programming February 11, 2004

  

ADO.NET

Page 53: Visual Basic.NET Programming ADO Programming February 11, 2004

DataAdapters

• Bridge between a data source and a DataSet

• The DataAdapter Fill() method is used to retrieve data from the database and to populate the DataSet

• Using the DataAdapter to mediate between the DataSet and the database allows a DataSet to represent more than one database or data source

Page 54: Visual Basic.NET Programming ADO Programming February 11, 2004

DBCommand and DBConnection• DBConnection object represents a connection to a

data source.

• DBCommand object allows you to send a command (typically a SQL statement or stored procedure) to the database.

• Both are implicitly created when you create a database, but they may also be explicitly created and accessed.

Page 55: Visual Basic.NET Programming ADO Programming February 11, 2004

DataSets

• Replaces the Old Recordset

• Standalone Relational Data Structure

• Completely Separate From the Server

• Resides with Client

• Contains one or more tables, plus table relationships, full subset of database

• Can be used to update data back in the source database

Page 56: Visual Basic.NET Programming ADO Programming February 11, 2004

Navigating a DataSet Dim ds As DataSet = New DataSet()

Dim dt As DataTable

Dim rw As DataRow

Dim cl As DataColumn

dt = ds.Tables.Item("Books")

For Each rw In dt.Rows

For Each cl In dt.Columns

tmpStr = rw(cl)

Next cl

Nexr rw

Page 57: Visual Basic.NET Programming ADO Programming February 11, 2004

XML Output From DataSetDim strXML As String

strXML = ds.GetXml()

Dim wlf As WriteListingFile = New WriteListingFile()

wlf.GetFileToOpen()

wlf.WriteLine(strXML)

wlf.Close()

Page 58: Visual Basic.NET Programming ADO Programming February 11, 2004

Sample XML Output-- <NewDataSet>-- <Books>

-<Title>Family Honor</Title>-<Author>Robert Parker</Author>-<Publisher>G.P. Putnam / the Penquin Group</Publisher>-<Copyright>1999</Copyright>-<Comments>A Sunny Randall novel.</Comments>

-   </Books>-- <Books>

-  <Title>Hugger Mugger</Title>-  <Author>Robert Parker</Author>-  <Publisher>G.P. Putnam / the Penquin Group</Publisher>-  <Copyright>2000</Copyright>-  <Comments>A Spenser Novel.</Comments> </Books>  </NewDataSet>

Page 59: Visual Basic.NET Programming ADO Programming February 11, 2004

Database Types

• SQL– SQL Server Version 7– SQL Server Version 2000

• OleDB– Microsoft Access

• ODBC– MySQL

Page 60: Visual Basic.NET Programming ADO Programming February 11, 2004

.NET Framework Data Providers

.NET Framework Data Provider for SQL Server

For Microsoft® SQL Server™ 7.0 or later.

.NET Framework Data Provider for OLE DB

For data sources exposed using OLE DB.

ODBC .NET Framework Data Provider

For data sources exposed using ODBC.

Page 61: Visual Basic.NET Programming ADO Programming February 11, 2004

ADO.NETADO.NET is the strategic application-level interface for providing data access services in the Microsoft .NET Platform. You can use ADO.NET to access data sources using the new .NET Framework data providers. These data providers include:

– .NET Framework Data Provider for SQL Server. – .NET Framework Data Provider for OLE DB. – .NET Framework Data Provider for ODBC. – .NET Framework Data Provider for Oracle.

These data providers support a variety of development needs, including middle-tier business objects using live connections to data in relational databases and other stores.

Page 62: Visual Basic.NET Programming ADO Programming February 11, 2004

Comparison Chart

Data Base Type Connection Object Adapter Object

SQL

(SQL Server)

SQLConnection SQLDataAdapter

OleDB

(Microsoft Access)

OleDBConnection OleDBDataAdapter

ODBC

(MySQL)

ODBCConnection OdbcDataAdapter

Page 63: Visual Basic.NET Programming ADO Programming February 11, 2004

SQL (SQL Server)

Imports System.Data.SqlClient

Private cn As SqlConnection = New System.Data.SqlClient.SqlConnection() Private adpt As SqlDataAdapter Private ds As DataSet = New DataSet() Dim sqlString As String = “SELECT * FROM Books” If cn.State <> ConnectionState.Open Then cn.ConnectionString = "Initial Catalog=Books;

Data Source=localhost;Integrated Security=SSPI;" cn.Open() End If

adpt = New SqlDataAdapter(sqlString , cn)adpt.Fill(ds, "Books")

Page 64: Visual Basic.NET Programming ADO Programming February 11, 2004

OleDB (Microsoft Access)

Imports System.Data.OleDb

Private cn As OleDbConnection = New OleDbConnection() Private adpt As OleDBDataAdapter Private ds As DataSet = New DataSet() Dim sqlString As String = “SELECT * FROM Books” If cn.State <> ConnectionState.Open Then cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;

Data Source=C:\…\Books.mdb“ Full Path cn.Open() End If

adpt = New OleDBDataAdapter(sqlString , cn)adpt.Fill(ds, "Books")

Page 65: Visual Basic.NET Programming ADO Programming February 11, 2004

ODBC (MySQL Database)

Imports Microsoft.Data.Odbc

Private cn As ODBCConnection = New ODBCConnection() Private adpt As OdbcDataAdapter Private ds As DataSet = New DataSet() Dim sqlString As String = “SELECT * FROM Books” If cn.State <> ConnectionState.Open Then cn.ConnectionString = "FIL=MySQL;DSN=MySQL_Books" cn.Open() End If

adpt = New OdbcDataAdapter(sqlString , cn)adpt.Fill(ds, "Books")

Page 66: Visual Basic.NET Programming ADO Programming February 11, 2004
Page 67: Visual Basic.NET Programming ADO Programming February 11, 2004

Grid Control

Page 68: Visual Basic.NET Programming ADO Programming February 11, 2004

Grid Control

• Easy way to display a DataSet Table

Page 69: Visual Basic.NET Programming ADO Programming February 11, 2004

Data Grid Control

Private DataGrid1 As DataGrid() = New DataGrid()

Note: Above created using Form Design.

Private Sub Button1_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles Button1.Click

OleDbDataAdapter1.Fill(DataSet1)

DataGrid1.SetDataBinding(DataSet1, "Books")

End Sub

Page 70: Visual Basic.NET Programming ADO Programming February 11, 2004
Page 71: Visual Basic.NET Programming ADO Programming February 11, 2004
Page 72: Visual Basic.NET Programming ADO Programming February 11, 2004

Building a Simple Database Query using a Grid Control

Let’s jointly build a very simple ADO.NET Database Application.

Page 73: Visual Basic.NET Programming ADO Programming February 11, 2004

Simple Database Query1. Open a new Windows Form Project

2. Add a Button ("Update Grid")

3. Add an OleDBDataAdapter

4. Add a DataSet

5. Add a DataGrid

6. Double click on the Button and add these two lines of code

OleDbDataAdapter1.Fill(DataSet1) DataGrid1.SetDataBinding(DataSet1, "Books")

7. Run it...

Page 74: Visual Basic.NET Programming ADO Programming February 11, 2004

Hand Crafted Grid Populator Class Exercise

Page 75: Visual Basic.NET Programming ADO Programming February 11, 2004

Books Populator Class Exercise

Page 76: Visual Basic.NET Programming ADO Programming February 11, 2004
Page 77: Visual Basic.NET Programming ADO Programming February 11, 2004

Guestbook Database Homework Exercise

for February 18th