Introduction to ADO.NET 2.


Plain Talk .NET Framework Data Provider Operation without Connection to a Database Applications pp cat o s

Plain Talk

Categories of Objects
Connected Objects:
Connecting a database Read-only record set y Forward-only stream

Disconnected Objects:
No connection to a database Off-line operation Sorting, Searching, Filtering, Modifying

ADO.NET Architecture
.NET Framework Data Provider
Connection DataAdapter Transaction SelectCommand InsertCommand DataColumnCollection UpdateCommand ConstraintCollection DeleteCommand DataReader DataRelationCollection DataTable DataRowCollection D t R C ll ti Command Parameters




Connected Objects – Connection Obj t C ti Object
A Connection for communicating with a Database As an ADO Connection Object O O

Connected Objects – Command Obj t C d Object
Query Execute a Stored Procedure Any A SQL Command C d As an ADO Command Object

Connected Objects – DataReader Object D t R d Obj t
Data Row is Read-Only Read Only Keep one row only Forward-only stream F d l t

Connected Objects – DataAdapter Object D t Ad t Obj t
A Bridge for Disconnected Objects One DataAdapter mapping to one DataTable

Disconnected Objects – DataTable Obj t D t T bl Object
Retrieving data from the Rows property As an ADO Recordset Object

Disconnected Objects – DataSet Object D t S t Obj t
A container for DataTable objects Exchange easily with XML Docs. As A an ADO Recordset Obj t R d t Object

Disconnected Objects – DataRelation Object D t R l ti Obj t
Define a relation between DataTable objects i.e. Matster-to-Detail Define D fi a rule. i.e. Delete th d t il when t l i D l t the details h to delete the master"s record.

Disconnected Objects – DataView Object D t Vi Obj t
Define a rule. i e Sorting or Filtering a rule i.e. DataTable

.NET Framework Data Provider NET

Using the Connection Object (one)
Using a Pooling Connection by default g g y
( SQL Server)

Using a connection: ( VB + SQL Server )
Dim myConnection as SqlConnection myConnection.ConnectionString = “…” myConnection.Open() myConnection.Close () y

Create a Transaction Object synchronously
( VB+ SQL Server )
Dim mySqlTransaction as SqlTransaction mySqlTransaction = myConnections.BeginTransaction mySqlTransaction.Commit () mySqlTransaction.Rollback ()

Using the Connection Object (two)
Create a Command Object synchronously
Dim myCommand as SqlCommand myCommand = myConnection.CreateCommand

Other usages:
Property: State Methods: Open, Close Event: StateChange

Using the Command Object (one)
How to get a Command Object? Operation without a result set. Operation with a result set set. Operation with Parameters. Operation with a Stored Procedure with Parameters. Operation with a Stroed Procedure with a return value.

Using the Command Object (two)
How to get a Command Object?
( VB + SQL Server )
A) myCommand = myConnection.CreateCommand
myCommand.CommandText = “…”

B) myCommand = SqlCommand.Create () ) y q
myCommand.Connection = myConnection myCommand.CommandText = “…”

C) myCommand = SqlCommand.Create(mySqlStr, myConnection)

Using the Command Object (three)
Operation without a result set:
DML (Data Manipulation Language) Insert, Update Insert Update, Delete DDL (Data Definition Language) Create Table Alter View Drop Table and so on Table, View, Table, on. How to do?
myCommand.CommandText = “Update permis set…” myCommand.ExecuteNonQuery ()

Using the Command Object (four)
Operation with a result set
DataReader Object:
Call the ExecuteReader method of the Command object, rather than directly i th di tl using a constructor t t Don"t open another DataReader object in the same connection Forward-only stream Read-only result set Keep one row only How to do?
Dim myDataReader as SqlDataReader myCommand.CommandText = “select * from PermisUser"” myDataReader = myCommand.ExecuteReader While myDataReader.Read() Response.Write (myDataReader(0), myDataReader(1)) End While reader.Close()

Using the Command Object (five)
Read a field of data in the DataReader
Dim myDataReader as SqlDataReader myCommand.CommandText = "select emp_na from PermisUser" myDataReader = myCommand.ExecuteReader() myDataReader.Read() strEmpName = myDataReader.Item( "emp na" ).ToString() p y ( p_ ) g()

Special operation:
Dim sCount as String myCommand.CommandText = "select count(*) from PermisUser” sCount = myCommand.ExecuteScalar.ToString() myCommand ExecuteScalar ToString()

Using the Command Object (six)
Operation with Parameters ( VB + SQL Server )
myCommand.CommandText = "select emp na from CtpPermisUser where emp no = p_ p p_ @Param1” myCommand.Parameters.Add("@Param1", SqlDbType.VarChar) myCommand.Parameters(0).Value myCommand Parameters(0) Value = "92110015” 92110015 myDataReader = myCommand.ExecuteReader() myDataReader.Read() sResult = myDataReader.Item("emp_na").ToString()
SQL Server .NET Provider supports Parameters with the “@ + ParamName” format.

Using the Command Object (seven)
Operation with a Stored Procedure with Parameters ( VB + SQL Server )
myCommand.CommandText = "spGetCM” C dC dT t " G tCM” myCommand.CommandType = CommandType.StoredProcedure myCommand.Parameters.Add("@PlayDate", SqlDbType.VarChar) myCommand.Parameters.Add("@PlayDate2", SqlDbType.VarChar) myCommand Parameters Add("@PlayDate2" SqlDbType VarChar) myCommand.Parameters("@PlayDate").Value = "2004/01/12" myCommand.Parameters("@PlayDate2").Value = "2004/01/13" myDataReader = myCommand ExecuteReader() myCommand.ExecuteReader() myDataReader.Read() sResult = myDataReader.Item("CM_Na").ToString()

CommandType: Text (default), StoredProcedure, TableDirect

Using the Command Object (eight)
Operation with a Stored Procedure with a return value ( VB + SQL Server )
myCommand.CommandText = "spGetCM" myCommand.CommandType = CommandType.StoredProcedure myCommand.Parameters.Add("@Return_Value", SqlDbType.Int) myCommand.Parameters.Add("@PlayDate", SqlDbType.VarChar) C dP t Add("@Pl D t " S lDbT V Ch ) myCommand.Parameters.Add("@PlayDate2", SqlDbType.VarChar) myCommand.Parameters.Direction = ParameterDirection.RetuenValue myCommand.Parameters( @PlayDate ).Value myCommand.Parameters("@PlayDate").Value = "2004/01/12" 2004/01/12 myCommand.Parameters("@PlayDate2").Value = "2004/01/13" myCommand.ExecuteNonQuery() strResult = myCommand.Parameters("@Return_Value").Value.ToString()

Direction: Input (default), Output, InputOutput, ReturnValue

Using the DataAdapter Object (one)
A bridge between Connected Objects and Disconnected Objects. (DataSet, DataTable)

DataAdapter DataSet DataTable


Using the DataAdapter Object (two)
How to get a DataAdapter Object?
( VB + SQL Server )
Dim Di myDataAdapter as SqlDataAdapter D Ad S lD Ad A) myDataAdapter = SqlDataAdapter.Create(strSQLSelect, strConnection)
This is not a good idea. It will establish another connection.

B) myDataAdapter = SqlDataAdapter.Create(strSQLSelect, myConnection) myCommand SqlCommand.Create(strSQLSelect, m Connection) m Command = SqlCommand C eate(st SQLSelect myConnection) C) myDataAdapter = SqlDataAdapter.Create() myDataAdapter.SelectCommand = myCommand D) myDataAdapter = SqlDataAdapter.Create(myCommand)

Using the DataAdapter Object (three) g j
Move a result set from a DataAdapter to DataSet: Fill method.
Auto open an established connection which had be closed. Auto create a DataTable object in the DataSet. By default, the DataTable object name is Table. Fill with a result set with ColumnName Ordinal and ColumnName, Ordinal, DataType. Paging through a q y result. g g g query Move a result set from ADO to ADO.NET

Using the DataAdapter Object (four)
How to use the Fill? ( VB + SQL Server )
Dim myDataSet as DataSet myDataSet = DataSet.Create() myDataAdapter = SqlDataAdapter.Create(strSQLSelect, myConnection) A) myDataAdapter.Fill(myDataSet) myDataAdapter Fill(myDataSet) B) myDataAdapter.TableMappings.Add("Table", "Customers") myDataAdapter.Fill(myDataSet) C) myDataAdapter.Fill(myDataSet, "myTableName") D) myDataAdapter.Fill(myDataSet, nStartRow, nRows, "myTableName")
nStartRow is zero-base.

E) myDataAdapter.Fill(myDataTable)
If you have a DataTable object

Using the DataAdapter Object (five)
You will fill the same DataTable twice:
If your DataTable has no primary key:
The result set from the DataAdapter is appended.

If your DataTabel has a primary key:
DataTable is updated by the primary key key. Use the FillSchema method to let your DataTable get a primary key as its mapping table in our database.
myDataAdapter.FillSchema(myDataSet, SchemaType.Source) myDataAdapter FillSchema(myDataSet SchemaType Source)

Avoid that result set is duplicate in the DataTable. First t l Fi t to clear the DataTable, then fill D t T bl with a th D t T bl th DataTable ith new result set.

Using the DataAdapter Object (six)
Other usages:
Methods: Fill FillSchema Update Events: FillError RowUpdating RowUpdated R U d t d

Operation without Connection to a Database

Using the DataSet Object (one)
You can:
scroll, search, sort, and filter a DataSet object. define a master-detail relation relation. modify the DataSet of content. integrated with XML Doc Doc.

Using the DataSet Object (two)
How to get a DataSet object? ( VB + SQL Server )
Dim myDataSet as DataSet A) myDataSet = DataSet.Create() B) myDataSet = DataSet.Create("myDataSetName")

Using the DataSet Object (three)
Use the DataRow object
Read the 1st row, the 2nd column which name is Emp_Na. Emp Na ( VB + SQL Server )
myDataAdapter.Fill(myDataSet, "myTableName")
A) myDataSet.Tables(0).Rows(0)(1).ToString B) myDataSet.Tables("myTableName").Rows(0)("Emp_Na").ToString C) myDataSet.Tables.Item(0).Rows.Item(0).Item(1).ToString D) myDataSet.Tables.Item("myTableName").Rows.Item(0).Item("Emp_Na").ToString

Using the DataSet Object (four)
Use the DataColumn object
Read properties of the 2nd column which column name is Emp Na. ( VB + SQL Server ) Emp_Na.
myDataAdapter.Fill(myDataSet, "myTableName")
A) myDataSet.Tables("myTableName").Columns(1).ColumnName.ToString B) myDataSet.Tables( myTableName ).Columns( Emp_Na ).Ordinal.ToString myDataSet.Tables("myTableName").Columns("Emp Na").Ordinal.ToString C) myDataSet.Tables("myTableName").Columns("Emp_Na").DataType.ToString

Using the DataSet Object (five)
Other usages
AcceptChanges RejectChanges GetChanges Clear Clone Copy Cop Merge Reset GetXml GetXmlSchema ReadXml ReadXmlSchema WriteXml WriteXmlSchema

Using the DataTable Object (one)
One DataTable exists in one DataSet only.
How to get it? ( VB + SQL Server ) g
A) myAdapter.Fill(myDataSet, "TableName") B) myAdapter.FillSchema(myDataSet, SchemaType.Source, "TableName") ) C) Dim myDataTable as DataTable Dim myColumn as DataColumn myDataTable = myDataSet.Tables.Add("TableName") myDataSet.Tables.Add( TableName ) myColumn = myDataTable.Add("Emp_No") myColumn.MaxLength = 10
Create a DataTable with a string type of Emp_No field. Emp No

myColumn = myDataTable.Add("HowOld", TypeOf(Integer))

Using the DataTable Object (two)
Add Constraints: ( VB + SQL Server )
AllowDBNull myColumn.AllowDBNull myColumn AllowDBNull = False ReadOnly myColumn.ReadOnly myColumn ReadOnly = True Unique myColumn.Unique myColumn Unique = True Column of MaxLength myColumn.MaxLength myColumn MaxLength = 5

Using the DataTable Object (three)
Primary Key Co st a t a y ey Constraint? Combine two fields for a Primary Key. ( VB + SQL Server )
Dim aryColumn as DataColum() aryColumn(0) = myDataTable.Columns.Add( Emp_No , myDataTable Columns Add("Emp No" TypeOf(Integer)) aryColumn(1) = myDataTable.Columns.Add("Emp_Name") myDataTable.PrimaryKey = aryColumn D t T bl P i K C l

Using the DataTable Object (four)
Foreign Key Constraint? Use the ConstraintCollection. ( VB + SQL Server )
Dim myForeignKey as ForeignKeyConstraint Dim myMasterCol, myDetailCol as DataColumn y , y myForeignKey = ForeignKeyConstraint.Create(myMasterCol, myDetailCol) myDataTable.Constraints.Add(myForeignKey)

Using the DataTable Object (five)
Can I add a calculated field? ( VB + SQL Server )
Dim strSubtotal as String strSubtotal = "AmountFieldName * CostFieldName" myDataTable.Columns.Add("myCalcFieldName", TypeOf(Integer), strSubtotal)
Any functions can be put inside the strSubtotal.

Using the DataTable Object (six)
Insert: se t
If your DataTable is…
Emp_No Emp No 92010001 92010002 Emp_Name Emp Name Andy Bill
( VB + SQL Server )

Emp_Birth Emp Birth 1965/01/21 1970/08/04

Emp_Salary Emp Salary 32000 29000

Dim myRow as DataRow myRow = myDataTable NewRow() myDataTable.NewRow() myRow("Emp_No") = "92090020" myRow("Emp_Name") = "Tom" y ( p ) myDataTable.Rows.Add(myRow)

// insertion

// don"t forget

Maybe you use the myDataTable.LoadDataRow(…)

Using the DataTable Object (seven)
Dim theRow as DataRow theRow = myDataTable.Rows.Find("92010002") If theRow Is Nothing then ShowMessage("Primary-Key Value not found.") Else theRow("Emp_Salary") = 33000 or … Else begin theRow.BeginEdit theRow( Emp_Salary ) theRow("Emp Salary") = 33000 theRow.EndEdit End

Reference Method: CancelEdit() Events: RowChanging RowChanged ColumnChanging ColumnChanged C l Ch d

Using the DataTable Object (eight)
Use the Delete() to mark. Use the Remove() / R U th R () RemoveAt() t remove the row At() to th truly. Use the Clear() to remove all rows rows.
theRow.Delete() theRow Delete() or myDataTable.Remove(theRow) or myDataTable.Clear()

Using the DataTable Object (nine)
Verify the state of the row – RowState property

Constant Detached

Value 1

The row has been created but is not part of any DataRowCollection. DataRowCollection. A DataRow is in this state immediately after it has been created and before it is added to a collection, or if it has been removed from a collection. The row has not changed since AcceptChanges was last called. The row has been added to a DataRowCollection, and DataRowCollection, AcceptChanges has not been called. The row was deleted using the Delete method of the DataRow. DataRow. The row has been modified and AcceptChanges has not been called.

Unchanged Added Deleted D l t d Modified

2 4 8 16

Using the DataTable Object (ten)
DataRowVersion Enumeration Enumeration.
sResult = myDataTable.Rows("Emp_Name", DataRowVersion.Current).ToString

( VB+ SQL Server )

Using the DataTable Object (eleven)
Other usages
AcceptChanges p g RejectChanges GetChanges Clear Clone Copy Compute Reset BeginLoadData g EndLoadData ImportRow

DataColumn Objects
Other usages
Properties: Caption DefaultValue Table

DataRow Objects
Other usages
RowError Table

AcceptChanges RejectChanges CancelEdit GetChildRows GetParentRow GetParentRows GetParentRo s SetParentRow IsNull

Use the DataRelation Object (one)
Make a relation between DataTable-s. DataTable s.
How to get it?
Dim myRelation as DataRelation Dim myCustTable, myOrderTable as DataTable myRelation = DataRelation.Create( RelationName , DataRelation Create("RelationName" myCustTable.Columns("CustID"), myOrderTable.Columns("CustID")) myDataSet.Relations.Add(myRelation)
Maybe the 2nd & 3rd parameters are the "array of DataColumn".

Use the DataRelation Object (two)
Get the Details:
Dim theCustRow, theOrderRow as DataRow For theOrderRow in theCustRow.GetChildRows("RelationName") do ShowMessage(theOrderRow("ProdName").ToString)

Get the Master from one Detail?
theCustRow = theOrderRow.GetParentRow("RelationName") ( ) ShowMessage(theCustRow("CustName").ToString)

How about th G tP H b t the GetParentRows()? tR ()?

Use the DataRelation Object (three)
If you establish a DataRelation object … object,
UniqueConstraint is added. ForeignKeyConstraint is added added. Exist constraints are added.

Use the DataRelation Object (four)
Other usages
Properties: ChildTable ParentTable Nested


Searching, Sorting, Filtering (one)
Searching: Find()
Find a row by the Primary Key.
The Primary Key included only one column. theRow = myDataTable.Rows.Find("myProdId") or, the primary key is established by two columns. Dim aryKey as object() aryKey(0) = nSerialNo aryKey(1) = "myProdId" theRow = myDataTable.Rows.Find(aryKey)

Searching, Sorting, Filtering (two)
Searching: Select()
Find rows with conditions.
Dim theRows as DataRow() Dim strCondition as String strCondition = "ProdType = ""PO"" and Cost > 10000 and ID like ""A%""" theRows = myDataTable.Select(strCondition)

Sorting: S l t() S ti Select()
Var strSort : String strSort = "Cost Desc" theRows = myDataTable.Select(strCondition, strSort)

Searching, Sorting, Filtering (three)
Searching: Select() with DataViewRowState
Searching changed rows inside the DataTable.
Dim enuDvrs as DataViewRowState enuDvrs = DataViewRowState.Added or DataViewRowState.Deleted theRows = myDataTable.Select("", "", enuDvrs)

Searching, Sorting, Filtering (four)
DataView objects? Not a SQL command. One DataView is mapping to one DataTable DataTable. A DataTable must have a TableName. Including all columns from one DataTable. Searching, sorting, filtering, editing, and g, g, g, g, navigation.

Searching, Sorting, Filtering (five)
Get a DataView object:
Dim myDataTable as DataTable Dim myDataView as DataView myDataTable = myDataAdapter.Fill(myDataSet, " T bl N D t T bl D t Ad t Fill( D t S t "myTableName") ") myDataView = DataView.Create(myDataTable)

Searching, Sorting, Filtering (six)
Retrieve rows from a DataView object: j
Dim enuDvrs as DataViewRowState enuDvrs = D Vi R S D DataViewRowState.Added or D Vi R S Add d DataViewRowState.Deleted D l d myDataView = DataView.Create(myDataTable, "ProdNo like ""S%"" ", Cost Desc" "Cost Desc , enuDvrs) or myDataView = DataView.Create DataView Create myDataView.Table = myDataTable myDataView.RowFilter = "ProdNo like ""S%""" myDataView.Sort = "Cost Desc" y myDataView.RowStateFilter = enuDvrs

Searching, Sorting, Filtering (seven)
Browsing a row in a DataView:
Use the Count property.
Dim theRowView : DataRowView For nRowIndex = 0 to myDataView.Count - 1 theRowView = myDataView(nRowIndex) ShowMessage(theRowView("theFieldName").ToString) Next or For nRowIndex = 0 to myDataView.Count - 1 sResult = myDataView(nRowIndex)("theFieldName") ToString myDataView(nRowIndex)( theFieldName ).ToString ShowMessage(sResult) Next

Use the GetEnumerator() method.

Searching, Sorting Searching Sorting, Filtering (eight)
Find() in the DataView object object.
DataView Object Searching Condition Found Not Found DataTable.Rows

By Sorting Fields
Row Index -1

By Primary Key Fields
DataRow object Nil, Nil Null

FindRows() ?
Return an array of DataRowView objects.
Dim aryRows as Object() aryRows = myDataView.FindRows(mySearchingValue) myDataView FindRows(mySearchingValue) If ( Length(aryRows) > 0 ) then …

Editing with DataRowView
Add a new row. row
Dim theRowView as DataRowView theRowView = myDataView.AddNew() theRowView("ProdName") = "xxx" theRowView.EndEdit() // update the DataTable object

Modify M dif a row.
theRowView.BeginEdit() theRowView("ProdName") = "yyy" theRowView.EndEdit()

Delete a row.

DataView & DataRowView Objeccts
Other usages:
DataView objects Methods: CopyTo, Delete CopyTo Properties: AllowDelete, AllowEdit, AllowNew, RowStateFilter DataRowView objects Methods: CancelEdit, CreateChildView Properties: IsEdit, IsNew Item IsEdit IsNew,

From DataSet to Database (one)
Intermediate: SqlDataAdapter Objects Requirement:
SqlDataAdapter.InsertCommand SqlDataAdapter.DeleteCommand S lD t Ad t D l t C d SqlDataAdapter.UpdateCommand SqlCommand.Connection SqlCommand.Parameters

From DataSet to Database (two)
strSQL = "insert into CustTable(CustNo) values (@CustNo)" myDataAdapter.InsertCommand.Connection = mySqlConnection D t Ad t I tC dC ti S lC ti myDataAdapter.InsertCommand.CommandText = strSQL myDataAdapter.InsertCommand.Parameters.Add("@CustNo", SqlDbType.VarChar)

Execute E t
Dim theRow as DataRow myDataAdapter.InsertCommand.Parameters("@CustNo").Value = y p ( @ ) theRow("CustNo").ToString() myDataAdapter.InsertCommand.ExecuteNonQuery()

From DataSet to Database (three)
strSQL = "delete from CustTable where CustNo = @CustNo" myDataAdapter.DeleteCommand.Connection = mySqlConnection myDataAdapter.DeleteCommand.CommandText = strSQL myDataAdapter.DeleteCommand.Parameters.Add("@CustNo", SqlDbType.VarChar)

Dim theRow as DataRow myDataAdapter.DeleteCommand.Parameters("@CustNo").Value = theRow( CustNo , theRow("CustNo", DataRowVersion.Original).ToString() myDataAdapter.DeleteCommand.ExecuteNonQuery()

From DataSet to Database (four)
strSQL = "update CustTable set CustType = @CustType_New where CustType = @CustType" myDataAdapter.UpdateCommand.Connection = mySqlConnection y p p y q myDataAdapter.UpdateCommand.CommandText = strSQL myDataAdapter.UpdateCommand.Parameters.Add("@CustType_New", Sq b ype a C a ) SqlDbType.VarChar) myDataAdapter.UpdateCommand.Parameters.Add("@CustType", SqlDbType.VarChar)

Execute E ec te
Dim theRow as DataRow myDataAdapter.UpdateCommand.Parameters("@CustType_New").Value = theRow( CustType , theRow("CustType", DataRowVersion.Current).ToString() myDataAdapter.UpdateCommand.Parameters("@CustType").Value = theRow("CustType", DataRowVersion.Original).ToString() g ) g() myDataAdapter.UpdateCommand.ExecuteNonQuery()

From DataSet to Database (five)
Updated the Database Client? Database.
Only AcceptChanges()

strXML = myDataSet GetXml() myDataSet.GetXml()
The strXML is a string list table by table.

myDataSet.WriteXML(“C:\myXMLFile.xml”, XMLW it M d W it S h D t S t W it XML(“C \ XMLFil l” XMLWriteMode.WriteSchema) )

End & Thank you. y
Author : Benjamin Editor : Albert

Sign up to vote on this title
UsefulNot useful