Copyright Scott-Jones Publishing, 2004-2005. All rights reserved. 3: ADO.NET Databases Updated 9/5/2004 Copyright Scott-Jones Publishing, 2004-2005. All rights reserved.
Overview Introduction to ADO.NET Using Data-Bound Controls Navigating, Adding, and Removing Rows Selecting DataTable Rows Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 2
3.1 Introduction to ADO.NET Provides access to database data sources Microsoft SQL Server Microsoft Access databases that support OLE DB and XML (many do this) ADO designed for client-server model ADO.NET designed for internet applications A more loose connection between web client and server Supports XML, an internet data transmission standard Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 3
Two ADO.NET Modes ADO.NET supports a connected and disconnected mode database connection kept open while reading all data rows can only be accessed in forward direction read-only access to data Disconnected entire database table copied into memory connection closed program works with the in-memory copy called a dataset Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 4
Reading From a Database We use disconnected mode in Chapter 3 VB.NET uses 3 related classes a database connection object defines access to the DB a data adapter object transfers data from DB to dataset a dataset object is used as the data container Visual Studio used to create and configure these objects Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 5
Database Basics Database – collection of one or more tables, each containing data related to a particular topic Table – logical grouping of related information Departments table example: Each row can be called a record Each column can be called a field Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 6
Primary Key Primary key consists of one or more columns that uniquely identify each table row Required when performing table updates Example: dept_id is the primary key Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 7
Clustered Primary Key Product Sales table example no column contains unique values we can combine date, product_id, and customer_id columns to form a composite key Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 8
Designing Database Tables Database schema design of tables, columns, and relationships between tables Principles avoid duplication of data create separate tables linked by a common column Database relationships one to one one to many many to many Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 9
One to Many Relationship Departments and Employee tables, linked by dept_id Employee table contains integer dept_id Table relationships will be explored more fully in Chapter 5. Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 10
Microsoft Access Data Types Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 11
Data Sources and Connections ADO.NET data flow Only one connection object needed for the database One connection can support multiple data adapters Each data adapter has a related dataset that it fills Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 12
Data Providers OLE DB .NET Data Provider SQL Server .NET Data Provider general use use for most databases, including Access SQL Server .NET Data Provider Used specifically for SQL Server databases faster than OLE DB Chapters 3 and 4 Chapter 5 onward Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 13
ADO.NET Connection Classes OleDbConnection connects to any OLE DB database minimal connection string two basic parameters: Provider=Microsoft.Jet.OLEDB.4.0; _ Data Source=SalesStaff.mdb SqlConection connects to SQL Server database Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 14
Database Connections Connection properties may be hard coded Or connection properties below may be set in code Connection has Open() and Close() methods Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 15
Data Adapter OleDbDataAdapter and SqlDataAdapter Actions: components in Visual Studio Toolbox Actions: reads data from data source into a dataset writes data from dataset to a data source Retrieves data by executing an SQL query Three ways to construct the SQL query: entered in Visual Studio thru the data adapter configuration in program code using SelectCommand property in a compiled stored procedure Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 16
Visual Studio Toolbox Wizards are provided for both OLE DB and SQL Server configuration under the Data tab in the toolbox MS-Access SQL Server Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 17
Datasets In-memory cache of records holding table data retrieved from one or more data sources (data adapters) Disconnected from data source updates are initially written to the dataset Underlying database changed only by a call to the data adapter's Update method Update method writes dataset changes to the database Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 18
DataSet Class System.Data namespace Important properties Tables: lists DataTable objects used to create dataset Dim tbl as DataTable For Each tbl in DsSalesStaff1.Tables List1.Items.Add(tbl.TableName) Next PrimaryKey: lists columns that make up the primary key tbl = dsSalesStaff1.SalesStaff Dim index as Integer For index = 0 to tbl.PrimaryKey.Length – 1 List1.Items.Add(tbl.PrimaryKey(index)) Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 19
Other Classes DataRow DataColumn holds a single row in a DataTable has properties corresponding to database columns For index = 0 to tbl.Rows.Count – 1 ListBox1.Items.Add(tbl.Rows(index).Item(0)) Next DataColumn describes a single column in a DataTable For index = 0 to tbl.Columns.Count -1 ListBox1.Items.Add(tbl.Columns(index)) Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 20
3.2 Using Data-Bound Controls Data binding permits controls to display and update dataset columns Data-aware control can bind itself to a dataset column DataBindings.Text property is assigned a column name Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 21
SalesStaff 1 Hands-on tutorial Shows how to set up a database connection Uses data-bound controls Displays a single row of the SalesStaff table Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 22
Structured Query Language (SQL) Universal language for retrieving data and manipulating databases Two varieties in Visual Basic .NET: Jet SQL (MS-Access) ANSI SQL (SQL Server) Most common statement: SELECT Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 23
SQL SELECT Statement SalesStaff example FirstName, HireDate, IsFullTime, LastName, Salary, StaffId FROM SalesStaff Create alias for any column name FirstName, LastName, Salary, HireDate AS DateHired Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 24
SQL – Setting Row Order ORDER BY statement Identify columns on which to sort Specify ASC or DESC direction Examples: ORDER BY LastName ORDER BY Salary ASC, HireDate DESC ASC is the default direction Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 25
3.3 Navigating, Adding, and Removing Rows Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 26
CurrencyManager Object Navigates between rows of a dataset bound to a form Properties: Count, integer with number of rows in the dataset Current, a DataRowView object that returns the current row Position, integer with current dataset row from 0 to count - 1 Methods: Refresh resets bound controls to values in dataset CancelCurrentEdit rejects changes to the current row EndCurrentEdit accepts changes to the current row RemoveAt deletes the row specified Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 27
CurrencyManager Object The WithEvents keyword allows your code to respond to CurrencyManager events such as .PositionChanged Obtained from the form's BindingContext: Private WithEvents currManager As CurrencyManager currManager = Me.BindingContext(dsSalesStaff1, _ "SalesStaff") Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 28
Moving Between Rows Add or subtract an integer from the form's CurrencyManager object Examples: move down one row: currManager.Position += 1 move up one row: currManager.Position -= 1 move to last row: currManager.Position = currManager.Count - 1 Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 29
Adding a New Row NewRow method creates a row having same structure as the existing dataset The process of adding a new row: First, create empty row in dataset for the SalesStaff table Dim newRow As System.Data.DataRow newRow = DsSalesStaff1.SalesStaffRow.newRow() Second, fill the columns with values newRow.StaffId = "104" newRow.FirstName = "Andrew" newRow.LastName = "Chang" OR... addForm.newRow = newRow (if controls are bound) Finally, add the new row to the table's Rows collection DsSalesStaff1.SalesStaff.Rows.Add(newRow) Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 30
Catching Exceptions Errors can occur when adding a new row to a dataset ConstraintException thrown if duplicate key value CancelEdit method used to reject the add attempt if an exception is thrown Try newRow.StaffId = "104" newRow.FirstName = "Andrew" newRow.LastName = "Chang" '(assign other column values . . .) dsSalesStaff1.SalesStaff.Rows.Add(newRow) Catch except As Exception MessageBox.Show(except.Message) newRow.CancelEdit() End Try Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 31
Common Operations Remove a Table Row: method 1: Use CurrencyManager.RemoveAt method currManager.RemoveAt(currManager.rowNbr) method 2: Use DataTable.Rows.Remove method dsSalesStaff1.SalesStaff.Rows.Remove(rowNbr) Update the Database with changes in the Dataset general form: DataAdapter.Update( DataSet ) example: daSalesStaff.Update(DsSalesStaff1) Reload the dataset daSalesStaff.Fill(DsSalesStaff1) Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 32
Checking for Null Values DataRow columns contain null if they have not been initialized Example: DbNull.Value checks for null LastName in the first row of table SalesStaff in dataset DsSalesStaff1: Dim row As DataRow = DsSalesStaff1.SalesStaff(0) If row("LastName") Is DbNull.Value Then 'LastName is null End If (see page 196) Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 33
Updating the SalesStaff Table SalesStaff 2 example Adds, removes, and updates dataset rows Updates the underlying database Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 34
Column Names as DataTable Properties The specific DataTable class contains a property for every database table column SalesStaff example Both statements below retrieve the contents of the Salary column from row 0 of the SalesStaff table: DsSalesStaff1.SalesStaff.Rows(0).Item(“Salary”) DsSalesStaff1.SalesStaff(0).Salary Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 35
Query Builder Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 36
Opening the Query Builder Tool Select data adapter object, view properties Expand SelectCommand Click on SelectCommand CommandText property Click on ellipsis button Query Builder window opens Provides a QBE interface to create SQL queries Change SalesStaff3 program to list by first name Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 37
SalesStaff 3 Hands-on example iterates through a dataset table displays names in a list box With DsSalesStaff1 Dim i As Integer For i = 0 To .SalesStaff.Count - 1 namesForm.lstNames.Items.Add( _ .SalesStaff(i).LastName & ", " & _ .SalesStaff(i).FirstName) Next End With Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 38
SalesStaff 3 Alternative code to insert names in list box For-Each loop with specific DataRow type: With DsSalesStaff1 Dim row As dsSalesStaff.SalesStaffRow For Each row In .SalesStaff.Rows namesForm.lstNames.Items.Add( _ row.LastName & ", " & _ row.FirstName) Next End With Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 39
Filling List and Combo Boxes Design mode: assign dataset name to the DataSource property asssign column name to the DisplayMember property At runtime: fill the dataset object from the data adapter SelectedIndexChanged event fires when list box or combo box is filled from the dataset use special logic to prevent program from reacting before the user has made a selection Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 40
ValueMember Property ListBox and ComboBox References a table column that will be a lookup value At run time, get the SelectedValue property Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 41
3.4 Selecting DataTable Rows Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 42
SQL WHERE Clause Filters or selects rows from a dataset table String literals are surrounded by single quotes Date literals MS-Access: surround with #...# SQL Server: surround with single quotes Examples: WHERE LastName = 'Gomez' WHERE Salary > 30000 WHERE LastName >= 'B' Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 43
SQL WHERE Clause LIKE and BETWEEN: All values beginning with letter A: WHERE LastName LIKE 'A%' All values beginning with 1 and ending with 4: WHERE StaffId LIKE '1_4' All values within a range: WHERE (HireDate BETWEEN #1/1/1992# AND #12/31/1999#) Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 44
Selecting Karate School Members Hands-on tutorial Karate database, Members table User selects a name from a combo box Program fills in remaining form fields from the dataset Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 45
Parameterized Queries Values in a WHERE clause can be provided at runtime Adds much flexibility to a static query Access and SQL Server work slightly differently: MS-Access, values provided at runtime identified by a ? SQL Server, values provided at runtime begin with @ next: examples Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 46
Parameterized Queries Using Access SQL contains ? for value to be provided: SELECT BirthDate, City, FirstName, LastName, MemberId, Phone, Street, Zip FROM Members WHERE (LastName = ?) VB sets the following data adapter property daMembers.SelectCommand.Parameters("LastName").Value = txtLastName.Text Alternative method uses an index instead of a name daMembers.SelectCommand.Parameters(0).Value = txtLastName.Text Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 47
Parameterized Queries using SQL Server SQL contains @field for value to be provided: SELECT BirthDate, City, FirstName, LastName, MemberId, Phone, Street, Zip FROM Members WHERE (LastName = @LastName) VB sets the following data adapter property daMembers.SelectCommand.Parameters("@LastName").Value = txtLastName.Text Alternative method uses an index instead of a name daMembers.SelectCommand.Parameters(0).Value _ = txtLastName.Text Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 48
Assigning Parameter Values Identify parameter by name or index position MS-Access: daMembers.SelectCommand.Parameters("LastName").Value _ = txtLastName.Text daMembers.SelectCommand.Parameters(0).Value _ = txtLastName.Text SQL Server: daMembers.SelectCommand.Parameters("@LastName").Value _ = txtLastName.Text Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 49
Creating an SQL Statement in Code Ultimate flexibility obtained by assigning the SQL in code Set data adapter SelectCommand.CommandText property An SQL query selecting a user entered customer name daSalesStaff.SelectCommand.CommandText = "SELECT FirstName, LastName FROM SalesStaff " & "WHERE LastName = '" & txtLastName.text & "';" Note the value provided by txtLastName.text must be enclosed in single quotes per standard SQL syntax Numeric fields do not require single quotes Date example: "WHERE HireDate = #" & txtHireDate.text & "#;" Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 50
The End Advanced Visual Basic .NET (Irvine, Liang, Gaddis) Slide 51