Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to ADO.NET. ADO.NET Objects Data Set.NET Applications Data Reader Command Object Connection Object Managed Data Provider (OLEDB) Database.

Similar presentations


Presentation on theme: "Introduction to ADO.NET. ADO.NET Objects Data Set.NET Applications Data Reader Command Object Connection Object Managed Data Provider (OLEDB) Database."— Presentation transcript:

1 Introduction to ADO.NET

2 ADO.NET Objects Data Set.NET Applications Data Reader Command Object Connection Object Managed Data Provider (OLEDB) Database Adapter

3 Connection with a Connection Object A connection object represents a unique session with a data source. Connection string: database, OLE DB provider, password, if any, security, etc. Use the Open/Close method to open/close a connection. Other functions: –Manage transaction: BeginTransaction(), Commit, rollBack.

4 Connection String Containing information about database, OLE DB provider, password, if any, security, etc. For Jet database: –="Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\sales2k.mdb"

5 Data Link Properties (Under the Advanced Tab of the Connection Dialog Window) Access permissions –Read—Read only. –ReadWrite—Read and write. –Share Deny None—Neither read nor write access can be denied to others. –Share Deny Read—Prevents others from opening in read mode. –Share Deny Write—Prevents others from opening in write mode. –Share Exclusive—Prevents others from opening in read/write mode. –Write—Write only.

6 Providers MSDASQL –Microsoft OLE DB Provider for ODBC Microsoft.Jet.OLEDB.3.51 Microsoft.Jet.OLEDB.4.0 MSDAORA – For Oracle SQLOLEDB – Microsoft SQL Server

7 Connection Object Example 1: –dim strConn as string ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\sales2k.mdb" –dim objConn as new OledbConnection(strConn) –objConn.open() Example 2: – Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\sales2k.mdb;User ID=Admin;Password=" Basic Methods: –Open, Close –BeginTransaction

8 Command Object The command object allows us to execute a SQL statement. Properties: –CommandType: Text, stored procedure, tableDirect –CommandText: SQL statement, procedure name, table name –Connection –Other properties: Parameters Basic Methods: –ExecuteReader: Creates a DataReader object that contains the results of the query. –ExecuteNonQuery: Change the data in a database without using a DataSet by executing SQL’s UPDATE, INSERT, or DELETE statements.

9 ExecuteReader Example dim strConn as string ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\sales2k.mdb" dim objConn as new OledbConnection(strConn) dim strSQL as string = "select * from customer;" dim objComm as new OledbCommand(strSQL,objConn) dim Results as string objConn.open() dim objDataReader as oledbDataReader objDataReader=objComm.executeReader()

10 Import NameSpace The Imports statement must appear before all other declarations in a file and cannot appear inside a class or module declaration. –Imports System.Data.OleDb –Public Class Form1 Note: To import a nameSpace for all forms/modules in a project: –Use Project Property Page: Imports

11 DataReader Object It is read-only and forward-only cursor. Basic Methods: –Read: Reads the current record and advances the pointer to the next record. It returns False if no more record in the DataReader. –Close: Closes the dataReader.

12 Read Records in a DataReader dim Results as string do while objDataReader.Read()=true Results+=objDataReader("cid") + “ “ + objDataReader("Cname") + vbCrLF loop Textbox1.text=Results Note: objDataReader.Item(0) Note: objDataReader.Item(“cid”)

13 Add Items from a DataReader to a Listbox Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\sales2k.mdb" Dim objConn As New OleDbConnection(strConn) Dim strSQL As String = "select cname from customer;" Dim objComm As New OleDbCommand(strSQL, objConn) objConn.Open() Dim objDataReader As OleDbDataReader objDataReader = objComm.ExecuteReader() Do While objDataReader.Read() = True LISTBOX1.Items.Add(objDataReader("cname")) Loop Note1: Listbox is not bound. 2. SelectedItem Note2: With the data binding you cannot issue the Add method.

14 Use a DataReader to Retrieve Summaries Dim sfCount, laCount, aCount, bCount, cCOunt As Integer objConn.Open() Dim objDataReader As OleDbDataReader objDataReader = objComm.ExecuteReader() Do While objDataReader.Read() = True If objDataReader("city") = "sf" Then sfCount += 1 ElseIf objDataReader("city") = "la" Then laCount += 1 End If If objDataReader("rating") = "a" Then aCount += 1 ElseIf objDataReader("rating") = "b" Then bCount += 1 Else cCOunt += 1 End If Loop TextBox1.Text = sfCount.ToString TextBox2.Text = laCount.ToString TextBox3.Text = aCount.ToString TextBox4.Text = bCount.ToString TextBox5.Text = cCOunt.ToString

15 Use SQL to Retrieve Summaries Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\sales2k.mdb" Dim objConn As New OleDbConnection(strConn) Dim strSQL As String = "select count(cid) as custCount from customer;" Dim objComm As New OleDbCommand(strSQL, objConn) Dim Results As String objConn.Open() Dim objDataReader As OleDbDataReader objDataReader = objComm.ExecuteReader() If objDataReader.Read = True Then MessageBox.Show(objDataReader("custCount").ToString) End If

16 Testing for Null If objDataReader.Read = True Then If IsDBNull(objDataReader("custCount")) Then TextBox1.Text = 0 Else TextBox1.Text = objDataReader("custCount").ToString End If Note: The keyword “Nothing” tests if an object is null.

17 Null Value Example Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\sales2k.mdb" Dim objConn As New OleDbConnection(strConn) Dim strSQL As String = "select * from customer where cid = '" & ListBox1.SelectedItem & "'" Dim objComm As New OleDbCommand(strSQL, objConn) objConn.Open() Dim objDataReader As OleDbDataReader objDataReader = objComm.ExecuteReader() objDataReader.Read() TextBox1.Text = objDataReader("Cname") TextBox2.Text = objDataReader("rating") ‘ Statement won’t work if Rating is null in database End Sub

18 Setting a Field to Null with a Update Statement Dim strSQLUpd As String = "Update Customer Set Rating = null Where cid = '" & ListBox1.SelectedItem & "'"

19 To Reuse a DataReader objDataReader.Close() objDataReader = objComm.ExecuteReader()

20 Error Handling Try objConn.Open() Dim objDataReader As OleDbDataReader objDataReader = objComm.ExecuteReader() Do While objDataReader.Read() = True Results += objDataReader("cid") + " " + objDataReader("Cname") + vbCrLf Loop TextBox1.Text = Results objConn.Close() Catch except As System.Exception MessageBox.Show(except.Message) End Try

21 Possible Database Errors SQL syntax errors Database connection not open Null Violate database constraints Referential integrity Field data type and length Primary key constraint

22 ExecuteNonQuery Example dim strSQLUpd as string="Update customer set rating = ‘A’” strSQLUpd=strSQLUpd & " where cname='" & CnameList.selectedItem.text & "'“ Dim objCommUpd As New OleDbCommand(strSQLUpd, objConn) objCommUpd.ExecuteNonQuery() Note: How many records affected by this command? ExecuteNonQuery method returns an integer indicating the number of record affected by the update command. Messagebox.Show( objCommUpd.ExecuteNonQuery())

23 Demo Create a project that do the following tasks: –Use a DataReader to retrieve customer IDs and populate a listbox. –Select a new rating from radio buttons for the selected customer. –Update customer’s rating using the ExecuteNonQuery method of a Command object.

24 Declare OleDB objects and create listbox Imports System.Data.OleDb Public Class Form3 Inherits System.Windows.Forms.Form Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\sales2k.mdb" Dim objConn As New OleDbConnection(strConn) Dim strSQL As String = "select cid from customer;" Dim objComm As New OleDbCommand(strSQL, objConn) Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load objConn.Open() Dim objDataReader As OleDbDataReader objDataReader = objComm.ExecuteReader() Do While objDataReader.Read() = True ListBox1.Items.Add(objDataReader("cid")) Loop objConn.Close() End Sub

25 Update customer rating Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click objConn.Open() Dim newRating As String If RadioButton1.Checked = True Then newRating = "A" ElseIf RadioButton2.Checked Then newRating = "B" Else newRating = "C" End If Dim strSQLUpd As String = "Update customer set rating = '" & newRating & "'" strSQLUpd = strSQLUpd & " where cid='" & ListBox1.SelectedItem & "'" Dim objCommUpd As New OleDbCommand(strSQLUpd, objConn) objCommUpd.ExecuteNonQuery() objConn.Close() End Sub

26 Use Command Object’s ExecuteNonQuery to Insert A New Record 1.Create unbound text boxes to enter new record. 2.Add an Insert button with the following handler Dim strSQLInsert As String strSQLInsert = "Insert into Customer values ('" strSQLInsert = strSQLInsert & TextBox1.Text & "','" & TextBox2.Text & "','" strSQLInsert = strSQLInsert & TextBox3.Text & "','" & TextBox4.Text & "')" Dim objCommInsert As New OleDbCommand(strSQLInsert, objConn) objCommInsert.ExecuteNonQuery()

27 Transaction OleDBTransaction –Dim objTrans As OleDbTransaction –objTrans= objConn.BeginTransaction() –objComm.Transaction = objTrans Methods: Commit, RollBack –objTrans.Commit

28 DataSet Object A DataSet object can hold several tables and relationships between tables. A DataSet is a set of disconnedted data. Data is extracted from the database and stored in the DataSet object. Updates to the DataSet must copy back to the database to make the changes permanent.

29 DataSet and Related Objects DataSet: Can contain multiple tables and relationships. DataTable object: Represents a table in the dataset. DataAdapter: This the object used to pass data between the database and the dataset. The Fill method copies the data into the dataset, and the Update method copies the updates back into the database. DataView: This represents a specific view of the DataTables held in the dataset.

30 DataSet and Related Objects DataSet Tables DataAdapter Commands Connection DataView DataSource

31 Structure of a Dataset Dataset Tables Data table Rows Data Row Columns Data Column Constraints Constraint Relations Data Relation

32 Reading Data into a Table dim strConn as string ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\sales2k.mdb" dim objConn as new OledbConnection(strConn) dim strSQLSelect as string = "select * from customer;" dim objDataSet as new Dataset() dim objAdapter as new OledbDataAdapter(strSQLSelect, objConn) objAdapter.Fill(objDataSet, "Cust")

33 Binding DataGrid with Code Imports System.Data.OleDb Public Class Form4 Inherits System.Windows.Forms.Form Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\sales2k.mdb" Dim objConn As New OleDbConnection(strConn) Dim objDataSet As New DataSet() Private Sub Form4_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim strSQL As String = "select * from customer;" Dim objAdapter As New OleDbDataAdapter(strSQL, objConn) objAdapter.Fill(objDataSet, "Cust") DataGrid1.DataSource = objDataSet DataGrid1.DataMember = "Cust" End Sub Note: Adapter’s Fill method is able to open the connection.

34 Binding a ListBox with Code Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\sales2k.mdb" Dim objConn As New OleDbConnection(strConn) Dim strSQL As String = "select * from customer;" Dim objDataSet As New DataSet() Dim objAdapter As New OleDbDataAdapter(strSQL, objConn) objAdapter.Fill(objDataSet, "Customer") ListBox1.DataSource = objDataSet.Tables("Customer") ListBox1.DisplayMember = "CID" End Sub Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged TextBox1.Text = ListBox1.SelectedItem.item("cname") End Sub Note: The FieldName for the DisplayMember is case-sensitive and should match the field name in the database.

35 Binding Textbox with Code Private Sub Form4_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\salesDB.mdb" Dim objConn As New OleDbConnection(strConn) Dim strSQLSelect As String = "select * from customer;" 'Dim objAdapter As New OleDbDataAdapter(strSQLSelect, objConn) Dim objAdapter As New OleDbDataAdapter Dim objComm As New OleDbCommand(strSQLSelect, objConn) objAdapter.SelectCommand = objComm objAdapter.Fill(objDataSet, "Customer") txtCID.DataBindings.Add("text", objDataSet, "customer.cid") txtCname.DataBindings.Add("text", objDataSet, "customer.cname") txtCity.DataBindings.Add("text", objDataSet, "customer.city") txtRating.DataBindings.Add("text", objDataSet, "customer.rating") End Sub Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNext.Click Me.BindingContext(objDataSet, "customer").Position += 1 End Sub

36 DataView Object A Better Way for Binding The DataView object exposes a complete table or a subset of the records from a table. Table’s DefaultView property: –Dim ObjDataView As New DataView() –ObjDataView.Table = objDataSet.Tables("Cust") –Or: ObjDataView = objDataSet.Tables("Cust").DefaultView DataView can be used as a DataSource in data binding.

37 Data Binding with DataView Object Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\sales2k.mdb" Dim objConn As New OleDbConnection(strConn) Dim objDataSet As New DataSet() Dim strSQL As String = "select * from customer;" Dim objAdapter As New OleDbDataAdapter(strSQL, objConn) objAdapter.Fill(objDataSet, "Cust") Dim ObjDataView As New DataView() ObjDataView = objDataSet.Tables("Cust").DefaultView DataGrid1.DataSource = ObjDataView

38 Selecting a Subset of Records with DataView’s RowFilter Property objDataView.RowFilter = criteria Note: The criteria can be a simple or complex condition.

39 DataView Example Dim ObjDataView As New DataView() Dim newRating As String If RadioButton1.Checked = True Then newRating = "A" ElseIf RadioButton2.Checked Then newRating = "B" Else newRating = "C" End If ObjDataView.Table = objDataSet.Tables("Cust") ObjDataView.RowFilter = "rating='" & newRating & "'" DataGrid1.Visible = True DataGrid1.DataSource = ObjDataView

40 Accessing Records in DataView Using DataView and DataRowView object’s Item property: objdataView = objDataSet.Tables("customer").DefaultView TextBox1.Text = objdataView.Item(rowIndex).Item(0) TextBox2.Text = objdataView.Item(rowIndex).Item(1) Move to the next record: rowIndex += 1 TextBox1.Text = objdataView.Item(rowIndex).Item(0) TextBox2.Text = objdataView.Item(rowIndex).Item(1) Note: To avoid out-of-bound, use the DataView’s Count property.

41 Creating multiple tables: One Adapter, One Table Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\salesDB.mdb" Dim objConn As New OleDbConnection(strConn) Dim strSQLCustomer As String = "select * from customer;" Dim strSQLOrders As String = "select * from orders" Dim objAdapterCust As New OleDbDataAdapter(strSQLCustomer, objConn) Dim objAdapterOrd As New OleDbDataAdapter(strSQLOrders, objConn) Dim objDataset As New DataSet objAdapterCust.Fill(objDataset, "Customer") objAdapterOrd.Fill(objDataset, "orders")

42 Creating Multiple Tables: One Adapter, Many Tables Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\salesDB.mdb" Dim objConn As New OleDbConnection(strConn) Dim strSQLCustomer As String = "select * from customer;" Dim strSQLOrders As String = "select * from orders" Dim objAdapter As New OleDbDataAdapter(strSQLCustomer, objConn) Dim objDataset As New DataSet objAdapter.Fill(objDataset, "Customer") objAdapter.SelectCommand.CommandText = strSQLOrders objAdapter.Fill(objDataset, "orders") DataGrid1.DataSource = objDataset

43 Binding Multiple Tables to a DataGrid (Example 1) DataGrid1.DataSource = objDataSet

44 Binding Multiple Tables to a DataGrid (Example 2) Dim ObjDataView As New DataView() Dim TableName As String If RadioButton1.Checked = True Then ObjDataView = objDataSet.Tables("Customer").DefaultView Else ObjDataView = objDataSet.Tables("Orders").DefaultView End If DataGrid1.DataSource = ObjDataView

45 Adding Relationship to a Dataset The Dataset object has a Relations property. It is a collection of DataRelations. We can use a relationship to enforce the referential integrity. To define a DataRelation: –DataRelObj=DataRelation(RelationName, ParentTable Field, ChildTableField) Dim objRel As DataRelation objRel = New DataRelation("custOrder", objDataset.tables("customer").columns("cid"), objDataset.tables("orders").columns("cid")) Adding a relation to the dataset: –objDataSet.Relations.Add(objRel)

46 Creating a Hierarchical DataGrid Dim objRel As DataRelation objRel = New DataRelation("custOrder", objDataSet.Tables("customer").Columns("cid"), objDataSet.Tables("orders").Columns("cid")) objDataSet.Relations.Add(objRel) DataGrid1.DataSource = objDataSet.Tables("customer")

47 DataTable’s Rows Property This is a collection of all the records in a table, a collection of DataRow objects. DataRow object’s properties and methods.

48 Accessing a Record with Index objAdapter.Fill(objDataSet, "Customer") TextBox1.Text = objDataSet.Tables("Customer").Rows(rowIndex).Item(0) TextBox2.Text = objDataSet.Tables("Customer").Rows(rowIndex).Item(1)

49 Access Rows in a DataRow Collection dim objTable as DataTable = objDataset.Tables("Customer") dim objRow as DataRow For each objRow in objTable.Rows strResult=strResult+“ " & objRow("cid") & " " & objRow("cname") & vbCrLf Next

50 DataRow object’s GetChildRows Method Returns a collection of rows from another table that are related as child rows to this row.

51 Displaying Parent/Child Records in a Relation Parent record displays in textboxes with navigation buttons. Child records display with a datagrid. Datagrid can be bound to a data relation: –dgOrders.DataSource = objDataSet –dgOrders.DataMember = "customer.custOrders" This example assumes textboxes are bound.

52 Imports System.Data.OleDb Public Class Form1 Dim objDataSet As New DataSet Dim currManager As CurrencyManager Private Sub MainSubFormwithRelation_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\salesDB.mdb" Dim objConn As New OleDbConnection(strConn) Dim strSQLCustomer As String = "select * from customer;" Dim strSQLOrders As String = "select * from orders" Dim objAdapter As New OleDbDataAdapter(strSQLCustomer, objConn) objAdapter.Fill(objDataSet, "Customer") objAdapter.SelectCommand.CommandText = strSQLOrders objAdapter.Fill(objDataSet, "orders") Dim objRel As New DataRelation("custOrders", objDataSet.Tables("Customer").Columns("cid"), objDataSet.Tables("orders").Columns("cid")) objDataSet.Relations.Add(objRel) txtCID.DataBindings.Add("text", objDataSet, "customer.cid") txtCname.DataBindings.Add("text", objDataSet, "customer.cname") txtCity.DataBindings.Add("text", objDataSet, "customer.city") txtRating.DataBindings.Add("text", objDataSet, "customer.rating") currManager = BindingContext(objDataSet, "customer") dgOrders.DataSource = objDataSet dgOrders.DataMember = "customer.custOrders" txtOrdCount.Text = objDataSet.Tables("customer").Rows(currManager.Position).GetChildRows("custOrders").Length.ToString End Sub

53 Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNext.Click currManager.Position += 1 txtOrdCount.Text = objDataSet.Tables("customer").Rows(currManager.Position).GetC hildRows("custOrders").Length.ToString End Sub Private Sub btnPrevious_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrevious.Click currManager.Position -= 1 txtOrdCount.Text = objDataSet.Tables("customer").Rows(currManager.Position).GetC hildRows("custOrders").Length.ToString End Sub

54 Parent/Child Form without a Relation This form lets users to select a CID from a listbox, then displays parent information in textboxes and child records in a datagrid by defining a dataview on Orders table based on selected CID. –Use View’s Filter Dim ObjDataView As New DataView() ObjDataView.Table = objDataSet.Tables(“Orders") ObjDataView.RowFilter = “cid='" & ListBox1.SelectedItem.item("cid") & "'" DataGrid1.DataSource = ObjDataView

55 Private Sub MainSubForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\salesDB.mdb" Dim objConn As New OleDbConnection(strConn) Dim strSQLCustomer As String = "select * from customer;" Dim strSQLOrders As String = "select * from orders" Dim objAdapter As New OleDbDataAdapter(strSQLCustomer, objConn) objAdapter.Fill(objDataSet, "Customer") objAdapter.SelectCommand.CommandText = strSQLOrders objAdapter.Fill(objDataSet, "orders") lstCID.DataSource = objDataSet.Tables("customer") lstCID.DisplayMember = "CID" End Sub Private Sub lstCID_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstCID.SelectedIndexChanged Dim ObjDataView As New DataView ObjDataView.Table = objDataSet.Tables("Orders") ObjDataView.RowFilter = "cid='" & lstCID.SelectedItem.item("cid") & "'" txtCname.Text = lstCID.SelectedItem.item("Cname") txtCity.Text = lstCID.SelectedItem.item("City") txtRating.Text = lstCID.SelectedItem.item("rating") txtOrdCount.Text = ObjDataView.Count.ToString dgOrders.DataSource = ObjDataView End Sub

56 DataTable’s Clone Method This technique uses the fact that the DataView of a table can be used as a DataSource in binding a data grid. Assuming a Customer/Orders relationship, for each customer record: –Use Table object’s Clone method to create a temporary child table structure. –Use Table object’s ImportRow method to import child records to the clone table. –Use the clone table’s DefaultView to bind the DataGrid.

57 Dim objRow As DataRow Dim drFound As DataRow drFound = objDataSet.Tables("Customer").Rows("0") TextBox1.Text = drFound.Item("cid") TextBox2.Text = drFound.Item("cname") Dim childTable As DataTable childTable = objDataSet.Tables("orders").Clone For Each objRow In drFound.GetChildRows(objOrderRel) childTable.ImportRow(objRow) Next DataGrid1.DataSource = childTable.DefaultView

58 Creating Parameter Queries 1. Specify the parameters in the SQL statement. –Dim strSQLOrder As String = "select * from orders where cid= ?;" 2. Add the parameters to the Command Object’s Parameters collection. –objComm.Parameters.Add("?cid", OleDbType.VarChar) 3. Assign the command to Adapter’s SelectCommand –objAdapter.SelectCommand=objComm 4. Set parameter’s value. –objAdapter.SelectCommand.Parameters("?cid").Value = ListBox1.SelectedItem.item("cid")

59 Parameter Query Example TextBox1.Text = ListBox1.SelectedItem.item("cname") Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\sales2k.mdb" Dim objConn As New OleDbConnection(strConn) objConn.Open() Dim strSQLOrder As String = "select * from orders where cid= ?;" Dim objComm As New OleDbCommand() Dim objAdapter As New OleDbDataAdapter() Dim objDataSet As New DataSet() objComm.Connection = objConn objComm.CommandType = CommandType.Text objComm.CommandText = strSQLOrder objComm.Parameters.Add("?cid", OleDbType.VarChar) objAdapter.SelectCommand = objComm objAdapter.SelectCommand.Parameters("?cid").Value = ListBox1.SelectedItem.item("cid") objAdapter.Fill(objDataSet, "Orders") DataGrid1.DataSource = objDataSet DataGrid1.DataMember = "orders"

60 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim strSQLOrder As String = "select * from customer where city= ?;" Dim objComm As New OleDbCommand() Dim objDataSet As New DataSet() objComm.Connection = objConn objComm.CommandType = CommandType.Text objComm.CommandText = strSQLOrder objComm.Parameters.Add("?city", OleDbType.VarChar) objAdapter.SelectCommand = objComm End Sub Private Sub RadioButton_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButton1.CheckedChanged, RadioButton2.CheckedChanged, RadioButton3.CheckedChanged Dim ObjDataView As New DataView() Dim city As String If RadioButton1.Checked = True Then city = "sf" ElseIf RadioButton2.Checked Then city = "la" Else city = "new york" End If objAdapter.SelectCommand.Parameters("?city").Value = city objDataSet.Clear() objAdapter.Fill(objDataSet, "cust") DataGrid1.DataSource = objDataSet DataGrid1.DataMember = "cust" End Sub

61 Multiple Forms: Where to import the oledb, and where to create the oledb objects Imports System.Data.OleDb Module Module1 Public strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\sales2k.mdb" Public objConn As New OleDbConnection(strConn) Public strSQLCust As String = "select * from customer;" Public strSQLOrder As String = "select * from orders;" Public objComm As New OleDbCommand() Public objAdapter As New OleDbDataAdapter() Public objDataSet As New DataSet() Public objRel As DataRelation Public strResult As String Public rowIndex As Integer = 0 Public ObjDataView As New DataView() Public Sub main() objComm.Connection = objConn objComm.CommandType = CommandType.Text objComm.CommandText = strSQLCust objAdapter.SelectCommand = objComm objConn.Open() objAdapter.Fill(objDataSet, "Customer") objComm.CommandText = strSQLOrder objAdapter.Fill(objDataSet, "Orders") End Sub End Module

62 Create Web Data Form Using ADO.Net Programming Model Demo: –Create ADO objects and bind them to a dataGrid. Control’s DataBind method –DataView

63 Using ToolBox/Data to Define Ado.Net Objects Connection: ToolBox/Data/OledbConnection –ConnectionString Command: ToolBox/Data/OledbCommand –Connection –CommandType –CommandText

64 Using DBMS Views Create views (queries) with DBMS Create commands to select records from views.

65 Using Stored Procedures in Access Note: Parameter queries are treated as procedures Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim objReader As OleDbDataReader Dim objComm As New OleDbCommand() objComm.Connection = OleDbConnection1 objComm.CommandType = CommandType.StoredProcedure objComm.CommandText = "CustP" objComm.Parameters.Add("CID", OleDbType.VarChar) OleDbConnection1.Open() objComm.Parameters(0).Value = InputBox("enter CID: ") objReader = objComm.ExecuteReader() If objReader.Read = True Then TextBox1.Text = objReader("cname") TextBox2.Text = objReader("rating") Else MessageBox.Show("record not exist") End If OleDbConnection1.Close() End Sub

66 Using TableDirect Command Type Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\sales2k.mdb" Dim objConn As New OleDbConnection() objConn.ConnectionString = strConn Dim objComm As New OleDbCommand() objComm.CommandType = CommandType.TableDirect objComm.CommandText = "customer" objComm.Connection = objConn Dim Results As String objConn.Open() Dim objDataReader As OleDbDataReader objDataReader = objComm.ExecuteReader()


Download ppt "Introduction to ADO.NET. ADO.NET Objects Data Set.NET Applications Data Reader Command Object Connection Object Managed Data Provider (OLEDB) Database."

Similar presentations


Ads by Google