Post on 03-Jun-2018
transcript
8/12/2019 Vb Net Data Access Ss 05
1/38
VB .NET Database Access
ISYS546
8/12/2019 Vb Net Data Access Ss 05
2/38
Microsoft Universal Data Access
ODBC: Open Database Connectivity A driver manager Used for relational databases
OLE DB: The OLE database protocol Allows a program to access information in many types
of data source. Data provider: databases, spreadsheets, etc.
ADO.NET: ActiveX Data Objects An Interface for OLE DB. Allow programmers to use a standard set of objects to
refer to any OLE DB data source.
8/12/2019 Vb Net Data Access Ss 05
3/38
.Net Applications
OLE DBProvider
OLE DBData Source
OLE DBProvider
ODBC
ODBCData Source
SQL ServerData Source
SQL Server.Net Data Provider
OLE DB.Net Data Provider
ADO.Net
8/12/2019 Vb Net Data Access Ss 05
4/38
Using ODBC
Windows 2000/2003: Control Panel /Administrative Tools/DataSource(ODBC)
Three types of data source names User DSN: usable only by you and only on the machine
currently using. System DSN: Any one using the machine can use.
File DSN: Can be copied and used by other computerswith the same driver installed.
8/12/2019 Vb Net Data Access Ss 05
5/38
VB.NET Database Tools
Database connection: Tool/Connect to database
Provider:MS Jet 4.0 OLE DB Provider Connection
Server Explorer Data connections:
Right click and Add Connection Tables, Views
Toolbox:Data tab Data Form Wizard
8/12/2019 Vb Net Data Access Ss 05
6/38
Steps to Retrieve Data
Establishes a connection to the database. Executes commands against the database. Store data results.
8/12/2019 Vb Net Data Access Ss 05
7/38
ADO.NET Objects
Data Set
.NET Applications
Data Reader
Command Object
Connection Object
Database
Adapter
8/12/2019 Vb Net Data Access Ss 05
8/38
ADO.NET Objects
Connection Object: Represent a connection to thedatabase.
Command Object: The command object allows usto execute a SQL statement or a stored procedure.
DataReader: It is a read-only and forward-only pointer into a table to retrieve records.
DataSet Object: A DataSet object can hold several
tables and relationships between tables. DataAdapter: This the object used to pass data
between the database and the dataset.
8/12/2019 Vb Net Data Access Ss 05
9/38
How to create an ADO.Net object?
Using Wizard Data Form Wizard
Data Adapter Wizard
Using code: Example: dim strConn as string ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source =
c:\sales2k.mdb" dim objConn as new OledbConnection(strConn) objConn.open()
8/12/2019 Vb Net Data Access Ss 05
10/38
Data Form Wizard
Creating a form with ADO.Net objects and data- bound controls to display and update information
in a dataset. Demo: Using Data Form Wizard to create a
navigational form. Project/Add Windows Form/Data Form Wizard Set connection Choose tables Display records in grid or in text boxes.
8/12/2019 Vb Net Data Access Ss 05
11/38
Adapter & Dataset Context Menu
Adapter: Properties:
Command objects Configure Adapter Generate dataset Preview data
Dataset: View Schema: Dataset/XML
8/12/2019 Vb Net Data Access Ss 05
12/38
Other Data Form Demos
Display records in text boxes. Add /Modify/Delete records. Hierarchical forms:
Parent/Child relationship
8/12/2019 Vb Net Data Access Ss 05
13/38
Creating A Database Application
Without Programming Creating a database application to display
information and update database.
A main form with buttons to open dataforms: DisplayInfo Enter New Modify Exit
8/12/2019 Vb Net Data Access Ss 05
14/38
Data Adapter Wizard
Configure Data Adapter and generating adataset:
Drag OledbDataAdapter (or databases table) tothe form. Use the Data Adapter Wizard to configure the
Adapter.
Right Click the Adapter to preview data andcreating dataset.
Bind the dataset to controls.
8/12/2019 Vb Net Data Access Ss 05
15/38
Data Binding
Connect a control or property to one or more dataelements.
Simple binding: Use simple binding to display afield value in controls that show Data Bindings inthe property window, such as text box or label.
Complex binding: Use complex binding to bindmore than one field to controls such as DataGridand list box. Use the controls Data Source andData Member to bind the data.
8/12/2019 Vb Net Data Access Ss 05
16/38
Creating Bound Controls
DataGrid control: Data Source property
Data Member property In the Form Load event, use Adapters Fill
method to load the dataset:
OleDbDataAdapter1.Fill(DataSet11)
8/12/2019 Vb Net Data Access Ss 05
17/38
Binding Text Box
Data Bindings property: Text: choose field
Add navigation buttons: The current record position within the dataset is
stored in a forms BindingContexts Position
property. This position is zero based. Add onemove to the next record, minus one move to the
previous record.
8/12/2019 Vb Net Data Access Ss 05
18/38
MoveNext and MoveLast Example
MoveNext: Me.BindingContext(DataSet21, "customer").Position += 1
MoveLast: Me.BindingContext(DataSet21, "customer").Position =
Me.BindingContext(DataSet21, "customer").Count -1
How to MovePrevious and MoveFirst? Note: The Position property takes care of the end of file
automatically.
8/12/2019 Vb Net Data Access Ss 05
19/38
CurrencyManager
Dim custCurrMgr As CurrencyManager Dim ordCurrMgr As CurrencyManager In a procedure:
ordCurrMgr = Me.BindingContext(Ds31, "orders") custCurrMgr = Me.BindingContext(Ds31, customer")
custCurrMgr.Position += 1 ordCurrMgr.Position += 1
8/12/2019 Vb Net Data Access Ss 05
20/38
Binding DataGrid
From Server Explorer, drag the table from adatabase connection (or from Data tab, drag
a oleDbAdapter) onto the form. Create dataset. Drag DataGrid and set the DataSource and
Data Member property. Use adapters Fill method to load the
dataset.
8/12/2019 Vb Net Data Access Ss 05
21/38
Displaying Many Tables with
One DataGrid Define one Adapter for each table. Create the dataset with multiple tables. Add a DataGrid control and set the
DataSource proeprty to the dataset nameand leave the DataMember property blank.
8/12/2019 Vb Net Data Access Ss 05
22/38
Creating Hierarchical Data Grid
Define two Adapters, one for the parent table andone for the child table.
Create the dataset. Right-click the dataset to View Schema Right-click the parent table and choose Add/New
Relation Add a DataGrid control and set the DataSource
proeprty to the dataset.parentTable and leave theDataMember property blank.
Note: DO File/SaveAll after creating the relation.
8/12/2019 Vb Net Data Access Ss 05
23/38
Binding ListBox
Example: Bind Customer Tables CID field to alistbox. Create a Adapter to retrieve CID (and Cname) fields ,
and generate the dataset. Add ListBox and set binding properties:
Data Source Display Member
Value Member: the actual values for items in the list box. Todisplay the selected items value in a text box, do: Textbox1.text = ListBox1.SelectedValue
Can we use TextBox1.text=ListBox1.SelectedItem? No!
8/12/2019 Vb Net Data Access Ss 05
24/38
Display Selected Record
Bound textbox: Me.BindingContext(DataSet11,
"customer").Position = ListBox1.SelectedIndex
Unbound textbox
8/12/2019 Vb Net Data Access Ss 05
25/38
ListBox SelectedItem Property
How to display the selected record in unboundtextbox? After binding to a data source, this property return a
DataRowView object. What is DataRowView?
Object Browser: System.Data
System.Data DataRowView: Item property
To retrieve a column from a DataRowView object(use 0-based index to identity a column):
ListBox1.SelectedItem.Item(1) Or: ListBox1.SelectedItem(1) Or: ListBox1.SelectedItem(Cname)
8/12/2019 Vb Net Data Access Ss 05
26/38
Using Object Browser
View/Object Browser DataSet object model:
System.Data DataSet Relations Tables
Rows
Columns
Use Object Browser to study objects properties,methods.
8/12/2019 Vb Net Data Access Ss 05
27/38
Collection Structure
Properties: Count
Item(index), 0-based index
Methods: Clear, Add, Insert, Remove, etc.
8/12/2019 Vb Net Data Access Ss 05
28/38
Navigate and Display Records in
Unbound Text Boxes Use code to assign field value to the text
boxs text property.
Example: Dim drFound As DataRow drFound = DataSet11.CUSTOMER.Rows(0)
Or DataSet11.Tables(CUSTOMER).Rows(0)
TextBox4.Text = drFound.Item("cname") Or drFound.Item(1)
Or: TextBox4.Text =DataSet11.CUSTOMER.Rows(0).Item(1)
Or: DataSet21.Tables.Item("customer").Rows.Item(0).Item(1)
8/12/2019 Vb Net Data Access Ss 05
29/38
Implement MoveNext Button
with Unbound ControlIf rowIndex < DataSet11.CUSTOMER.Rows.Count-1 Then
rowIndex += 1
TextBox1.Text = DataSet11.Tables("customer").Rows(rowIndex).Item(0)
TextBox2.Text = DataSet11.CUSTOMER.Rows(rowIndex).Item(1)
Else
MsgBox("out of bound")
End If
Note: MovePrevious, MoveLast, MoveFirst?
8/12/2019 Vb Net Data Access Ss 05
30/38
Using Object Browser to Study OleDB
Object System.Data
System.Data.OleDB OleDBConnection
Methods: New(), New(ConnectionString), Open(), Close() Properties: ConnectionString, DataBase, Provider, TimeOut
OleDBCommannd Methods: ExecuteReader, ExecuteNonQuery Properties: Connection, CommandType, CommandText,
Parameters OleDBDataAdapter
Methods: Fill Properties: SelectCommand, InsertCommand, DeleteCommand,
UpdateCommand.
8/12/2019 Vb Net Data Access Ss 05
31/38
Searching with the Find MethodAnother Way to Bind Listbox and Display
Selected Record Create an adapter to retrieve Customer
records and create a dataset.
Bind the CID field to the listbox. Use the Find method of Tables Rows
collection to find the record. Display the found record in unbound text
boxes.
8/12/2019 Vb Net Data Access Ss 05
32/38
Code Example
Private Sub ListBox1_SelectedIndexChanged(ByVal sender AsSystem.Object, ByVal e As System.EventArgs) HandlesListBox1.SelectedIndexChanged
Dim drFound As DataRow
drFound = DataSet41.CUSTOMER.Rows.Find(ListBox1.SelectedValue)
Assume SelectedValue is CID
TextBox1.Text = drFound.Item("cname")TextBox2.Text = drFound.Item("rating")
End Sub
Note: We can get the search value from other controls such as InputBoxand Textbox.
8/12/2019 Vb Net Data Access Ss 05
33/38
How to Determine If Record Exists
or NotDim foundRow As DataRowDim SearchValue as StringSearchValue=InputBox(Enter CID) foundRow = DataSet41.CUSTOMER.Rows.Find (SearchValue)If Not (foundRow Is Nothing) Then
TextBox1.Text = drFound.Item("cname")TextBox2.Text = drFound.Item("rating")
ElseMessagerbox.show(Record not exist)
End If
8/12/2019 Vb Net Data Access Ss 05
34/38
Creating Parameter Query with Adapter
Configuration Wizard Parameter query: Selection criteria is entered at
run time. Command objects Parameters property. Example: Orders table: OID, CID, Odate,
SalesPerson To create a parameter for the CID field:
In the Query Design windows criteria column of the CID field, addcriteria: =?
To assign the parameter value: OleDbDataAdapter2.SelectCommand.Parameters("cid").Value =
Demo: Get CID from a InputBox and display orders.
8/12/2019 Vb Net Data Access Ss 05
35/38
Parameter Query Example:
Select CID from a listBox and displayorders of the selected CID in a DataGrid Create and bind the listbox (specify the valueMember). Create a second adapter and define a parameter query. In the Query Design windows criteria column, add criteria: =? Generate a 2nd dataset (DataSet21 in this example) with the
parameter. Create and bind the DataGrid to the dataset. In the listboxs SelectedIndexChanged event, assign the selected
value to the parameter and fill the dataset:
DataSet21.Clear() OleDbDataAdapter2.SelectCommand.Parameters("cid").Value =ListBox1.SelectedValue
OleDbDataAdapter2.Fill(DataSet21)
8/12/2019 Vb Net Data Access Ss 05
36/38
Display Selected Record in Text Boxes
with Parameter Query Create and bind the listbox. Create a second adapter and define a parameter query.
In the Query Design windows criteria column, add criteria: =?
Generate the dataset with the parameter. Create and bind textboxes to the dataset. In the listboxs click event, assign the selected value to the
parameter and fill the dataset: DataSet11.Clear()
OleDbDataAdapter2.SelectCommand.Parameters("cid").Value =ListBox1.SelectedValue OleDbDataAdapter2.Fill(DataSet11)
8/12/2019 Vb Net Data Access Ss 05
37/38
Send Changes in a Bound DataGrid
Back to the Database Updating records in DataGrid:
New records are added at the end of the grid.
To delete a record, click the leftmost column to selectthe record, then press the delete key. Modify record
Add an Update button that use adapters update
method to send changes back to the data source: OledbDataAdapter1.Update(Dataset11)
8/12/2019 Vb Net Data Access Ss 05
38/38
Creating Parent/Child Form with
Binding Dataset contains Customer and Orders with
relation CustomerOrders. Bind the textboxes to Customer table. Bind the datagrid to the relation:
DataSource: Dataset DataMember: Customer/CustomerOrders
Note: Study the form created by the Data FormWizard.