ADO.net
ADO.net
Paladn.com
1
www.paladn.com
TABLE OF CONTENTS
2
www.paladn.com
3
www.paladn.com
Imports System.Data.SqlClient There is also support for the ODBC connections through Imports System.Data.ODBC These commands expose the objects needed to connect to the data source.
Data Retreival
Like ADO, ADO.Net uses a connection object to point to external data. Under the .Net model, a connection is opened, data is retrieved, and then the connection is closed. The closing of the connection is necessary to free up resources. The connection string (the part of the comment which identifies the source of the data, as well as access to it through username and password) is identical to the connection string grammar under the old model ADO. The first way to access data is after you have defined and opened the connection, invoke the command object providing it with a SELECT statement, or storedprocedure name with parameters. The Data Reader will allow the application to gain access to the returned resultset. An ExecuteReader method will allow a line by line reading of the data retrieved. However, be aware that this is a forward only dataset once a line is read, unless you save its contents somewhere, somewhere the data can be lost. The only way to make it available again is to re-establish the connection and read it again. The second method opens a connection, retrieves a recordset, then stores that recordset in an object called a DataSet. The DataSet acts and functions like a local database, storing the data retrieved even from multiple sources. It can even link and establish relationships between multiple tables. At the conclusion of the data retrieval, the connection is closed, so that in processing the DataSet is completely disconnected from the data source(s). The mapping of data between the DataSet and the outside data sources is handled by the DataAdapter object. In addition to keeping track of the connections to the data sources, the DataAdapter also facilitates the updating, deleting, and insertion of data back to the source.
4
www.paladn.com
XML
XML is the native format for ADO.Net. It is so tightly integrated that you can define and read schemas, and can seamlessly exchange data in the XLM format, both reading and writing with any application on any platform.
5
www.paladn.com
In a connected mode environment, after a connection is established with the data, the data is manipulated and returned using the command object. The command object is passed a SQL query SELECT statement, which is run by one of the Execute methods. The three Execute methods are ExecuteNonQuery (for updates or deletes or appends), Execute Reader (for returning datasets to the client), and ExecuteScalar (returns a single value). The command objects themselves are either of SqlCommand, OleDbCommand, or ODBCCommand types. And the principal properties are the command text (the sql statement, and the connection object previously created. ) Other properties are the CommandType, Transaction, CommandTimeout, Parameters, and UpdatedRowSource. Dim cmd as New SqlCommand cmd.connection=conn cmd.CommandText=SELECT * FROM tblBooks; Dim dr as SqlDataReader = cmd.ExecuteReader() The preceding code will execute a SQL command and put the results into a DataReader after having made and opened a connection. Had the SQL statement been an INSERT statement, the appropriate method would have been ExecuteNonQuery(), rather than ExecuteReader(). There is an additional Execute XMLReader() method which is new in SQL2000, and is used for processing SELECT queries from an XML dataset. ExecuteScalar() is another method used for returning a single value from a dataset.
Parameters
In the OleDb model, you can define parameters in the CommandText using question marks.
6
www.paladn.com
SELECT * from tblBooklist where YearPublished = ?; Then you need to create and define the parameter prior to passing them into the command object. Dim Parm as New OleDBParameter(YearPublished, OleDbType.Integer) Parm.Value=1994 cmd.Parameters.Add(parm) You can even have ADO.Net populate the list of parameters for you using the DeriveParameters method. Dim cmd as New SqlCommand(up_getshotgun, conn) cmd.CommandType=CommandType.StoredProcedure SqlCommandBuilder.DeriveParameters(cmd) Debug.writeline(cmd.parameters.count & parameters) For i = 0 to cmd.parameters.count-1 Debug.writeline(cmd.parameters(i).ParameterName) Next
Stored Procedures
Stored Procedures are handled using the parameters in the previous section and setting them with the Parameters.Add method. The only difference from the previous code is the calling of the stored procedure itself. This is accomplished using the CommandType property, rather than the CommandText property. Dim cmd as New SqlCommand(up_getshotgun, conn) cmd.CommandType=CommandType.StoredProcedure
7
www.paladn.com
8
www.paladn.com
Connection Timeout
Database
DataSource
ServerVersion
State
Returns state of current database in integers. Values can be Closed, Connecting, Open, Executing, Fetching, Broken
Provider
Returns the value of provider attribute as specified in connection string (Read Only) (OleDb Only)
PacketSize
WorkstationID
9
www.paladn.com
In the above table, the only property that is NOT read only is the connection string. Some folks say that it is the connection string that is the most difficult aspect of ADO and ADO.Net. If so, it is an easily learned one. A typical connection string consists of 4 items: The Provider, which specifies the name of the underlying OLEDB provider. Appropriate values are SQLOLEDB (for SQLServer), Microsoft.Jet.OLEDB.4.0 (for Microsoft Access) and MSDORA (for Oracle); The Data Source attribute, which shows the location of the database. It can be a path on a network, or the IP address of a machine on the net; The UserID and Password, which grant access permission to the database; The Initial Catalog, which specifies the name of the database in the data source. Here are some common configurations:
C#:
using System.Data.SqlClient; objqlConnection oSQLConn = new SqlConnection();oSQLConn.ConnectionString=connectstring;;oSQLConn.Open();
obj VB.NET:
Imports System.Data.SqlClient Dim objSQLConn As SqlConnection = New SqlConnection() objSQLConn.ConnectionString="connectstring" objSQLConn.Open()
10
www.paladn.com
For Oracle:
Provider=OraOLEDB.Oracle;Data Source=mydatabase;User Id=ElmerFudd;Password=wabbitt; Provider=OraOLEDB.Oracle;Data Source= mydatabase;OSAuthent=1;
C#:
using System.Data.OracleClient; OracleConnection objOracleConn = new OracleConnection(); objOracleConn.ConnectionString = my connectionstring; objOracleConn.Open();
VB.NET:
Imports System.Data.OracleClient Dim objOracleConn As OracleConnection = New OracleConnection() objOracleConn.ConnectionString = myconnectionstring objOracleConn.Open()
For MS Access:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\pathname\biblio.mdb;User Id=ElmerFudd;Password=wabbitt; Notice that the last instruction in the code using the method open(). After the connection has been made, and the data retrieved, you need to close the connection using the connection method close(). This should be done within an if statement which first checks whether the connection is, in fact, open: If (objConnection.state and ConnectionState.Open) <>0 Then objConnection.Close End If Note that the state property is 0 if the connection is already closed. Testing for a closed connection is necessary to prevent an error when you are invoking the close method.
11
www.paladn.com
The connection objects methods are: Open Close BeginTransaction ChangeDatabase CreateCommand Opens connection Closes connection Begins database transaction Changes the name of database connected to Creates a command object schema tables and associated restricted
Shared method which allows closing of connection pool when last connection is closed
Exception Handling
All ADO connection procedures should be protected with a Try/Catch Block. When dealing with a connection to another server, this is especially important to let your users know that it was the connection that failed, rather than the application code. Try connSQLNorthwind.ConnectionString = _ "Server=Jupiter;Database=pubs;Trusted_Connection=True;Connection Timeout = 10" Catch ExSQL As System.Data.SqlClient.SqlException Dim strErrorMsg As String Dim strerror As System.Data.SqlClient.SqlError For Each strerror In ExSQL.Errors Select Case strerror.Number Case 17 strErrorMsg = "Missing server" Case 4060 strErrorMsg = "Missing database"
12
www.paladn.com
Case 18456 strErrorMsg = "Missing user name or password" Case Else strErrorMsg = strerror.Message End Select MessageBox.Show(sErrorMsg, "SQL Server Error: " & strerror.Number, MessageBoxButtons.OK MessageBoxIcon.Error) Next
Catch ExcpInvOp As System.InvalidOperationException MessageBox.Show("Close the connection first!", _ "Invalid Operation MessageBoxButtons.OK, MessageBoxIcon.Error) Catch Excp As System.Exception ' generic exception handler MessageBox.Show(Excp.Message, "Unexpected Exception MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
13
www.paladn.com
14
www.paladn.com
statements. The NextResult method allows you to advance to the next recordset within the DataReader. Do while dr.NextResult Do while dr.Read Process stuff Loop Loop
15
www.paladn.com
16
www.paladn.com
Constructors
Visibility Constructor Parameters
public
DataTable
()
public
DataTable
( String tableName )
Properties
Visibility public public public public public public public public public public public public public public public public public public public Name CaseSensitive ChildRelations Columns Constraints Container DefaultView DesignMode DisplayExpression Value Type Boolean Accessibility [ Get , Set ]
DataRelationCollection [ Get ] DataColumnCollection ConstraintCollection IContainer DataView Boolean String [ Get ] [ Get ] [ Get ] [ Get ] [ Get ] [ Get , Set ] [ Get ] [ Get ] [ Get , Set ] [ Get , Set ] [ Get , Set ]
ExtendedProperties PropertyCollection HasErrors Locale MinimumCapacity Namespace ParentRelations Prefix PrimaryKey Rows Site TableName Boolean CultureInfo Int32 String
DataRelationCollection [ Get ] String DataColumn DataRowCollection ISite String [ Get , Set ] [ Get , Set ] [ Get ] [ Get , Set ] [ Get , Set ]
17
www.paladn.com
Methods
Visibility public public public public public public public public public public public public public public Name AcceptChanges BeginInit BeginLoadData Clear Clone Compute Copy EndInit EndLoadData GetChanges GetChanges GetErrors ImportRow LoadDataRow Parameters () () () () () ( String expression, String filter ) () () () ( DataRowState rowStates ) () () ( DataRow row ) ( Object values , Boolean fAcceptChanges ) public public public public NewRow RejectChanges Reset Select () () () ( String filterExpression, String sort, DataViewRowState recordStates ) public public Select Select ( String filterExpression ) () DataRow DataRow DataRow Void Void DataRow DataTable DataRow Void DataRow DataTable Void Void DataTable Return Type Void Void Void Void DataTable Object
18
www.paladn.com
public
Select
DataRow
public
ToString
()
String
Events
Multicast multicast multicast multicast multicast multicast multicast multicast Name ColumnChanged ColumnChanging Disposed RowChanged RowChanging RowDeleted RowDeleting Type DataColumnChangeEventHandler DataColumnChangeEventHandler EventHandler DataRowChangeEventHandler DataRowChangeEventHandler DataRowChangeEventHandler DataRowChangeEventHandler
19
www.paladn.com
public
Object
[ Get ]
public
Object
[ Get ]
public
Object
[ Get , Set ]
public
Object
[ Get , Set ]
public
ItemArray
Object
[ Get , Set ]
public
RowError
String
[ Get , Set ]
public
RowState
DataRowState [ Get ]
public
Table
DataTable
[ Get ]
20
www.paladn.com
Methods
Visibility public public public public public public public public Name AcceptChanges BeginEdit CancelEdit ClearErrors Delete EndEdit GetChildRows GetChildRows Parameters () () () () () () ( String relationName ) ( String relationName , DataRowVersion version ) DataRow GetChildRows ( DataRelation relation , DataRowVersion version ) public public public public public public GetChildRows GetColumnError GetColumnError GetColumnError GetColumnsInError GetParentRow ( DataRelation relation ) ( Int32 columnIndex ) ( String columnName ) ( DataColumn column ) () ( String relationName , DataRowVersion version ) DataColumn DataRow String String String DataRow DataRow Return Type Void Void Void Void Void Void ( String relationName ) DataRow
21
www.paladn.com
public public
GetParentRow GetParentRow
DataRow DataRow
public public
GetParentRow GetParentRows
DataRow DataRow
public public
GetParentRows GetParentRows
DataRow DataRow
( String relationName ) ( DataRowVersion version ) ( String columnName ) ( DataColumn column , DataRowVersion version )
22
www.paladn.com
public public
SetColumnError SetColumnError
Void Void
public
SetColumnError
Void
public
SetParentRow
Void
public
SetParentRow
( DataRow parentRow )
The DataSet is a much more powerful and complicated object than the DataReader. The DataReader is a read-only forward-only object wherein once a record is read it is gone, unless it is saved into an array. The DataSet and DataTable objects are virtualls datasets and tables which are used in client-side operations. Though there is no current record concept, the user is able to navigate between the rows using loops, either using the Rows collection of the DataTable object, or the DataRow object. For i=1 to 3 tblEmployee.Rows(i)(FirstName)=Daffy or dim dr as DataRow=tblEmployee.Rows(i) dr(LastName)=Duck Next
23
www.paladn.com
Dont forget that the DataSet is disconnected from the original server-side source of the data. So any changes in the DataSet will not be reflected in the source unless and until the DataSet and the Source are reconciled. You can find the status of any record by querying the RowState property of the DataRow object. The result will be one of the following: Detached, Added, Modified, Deleted, or Unchanged. Though the RowState property is read only, the DataRow has two properties which can change it: the AcceptChanges, and RejectChanges Properties. Of further note are the DataTable.ColumnChanging, the DataTable.ColumnChanged, the DataTable.RowChanging, and the DataTable.RowChanged events which allow you to trap and code for these events within your code. The DataView Object The function of the DataView object is to facilitate data binding of data to Windows forms and web pages. Additionally, it can be used along with the Select method od the DataTable Object to present subsets of records from tables. Use the RowFilter property to select which records are visible, and use the Sort property to order their presentation.
Constructors
Parameters () ( DataTable table ) ( DataTable table , , , String String RowState ) RowFilter Sort
DataViewRowState
24
www.paladn.com
Properties
Visibility public public public public public public public public public public public public public Name AllowDelete AllowNew ApplyDefaultSort Container Count DataViewManager DesignMode Item ( recordIndex ) RowFilter RowStateFilter Site Sort Table String DataViewRowState ISite String DataTable [ Get , Set ] [ Get , Set ] [ Get , Set ] [ Get , Set ] [ Get , Set ] Value Type Boolean Boolean Boolean IContainer Int32 DataViewManager Boolean Int32 DataRowView Accessibility [ Get , Set ] [ Get , Set ] [ Get , Set ] [ Get ] [ Get ] [ Get ] [ Get ] [ Get ]
Methods
Visibility public public public public public public public public public public Name AddNew BeginInit CopyTo Delete EndInit Find Find FindRows FindRows GetEnumerator Parameters () () ( Array array Int32 index ) ( Int32 index ) () ( Object key ) ( Object key ) ( Object key ) ( Object key ) () Void Void Int32 Int32 DataRowView DataRowView IEnumerator Return Type DataRowView Void , Void
25
www.paladn.com
Events
26
www.paladn.com