Introduction to ADO.NET

The .NET data access layer is called ADO.NET and consists of two major ways of dealing with data. The first way, and the easiest for developers familiar with SQL, is implemented in terms of the IDataReader interface. The second way is the DataSet.

Out of the box, .NET Framework Version 1.0 provides implementations of IDataReader in System.Data.SqlClient.SqlDataReader (for SQL Server data sources) and System.Data.OleDb.OleDbDataReader (for OLE data sources). .NET 1.1 adds the System.Data.Odbc and System.Data.OracleClient namespaces for access to ODBC and Oracle databases, respectively.

Tip

In fact, most of the classes in the System.Data.OleDb and System.Data.SqlClient namespaces simply provide implementations of interfaces in the System.Data namespace, so I’ll just refer to the interfaces by their interface names, such as IDataReader, until we get down to examples. If you want to learn more about ADO.NET, I suggest ADO.NET in a Nutshell, by Bill Hamilton and Matthew MacDonald (O’Reilly).

Before you can actually use the IDataReader to read data, you need to set up a connection to the database using the IDbConnection interface. Exactly how you do that depends on whether you’re using the SqlConnection or the OleDbConnection, but each one has a ConnectionString property that you can use to specify the database you’re connecting to.

Creating an IDbConnection does not actually create the physical connection to the database. In fact, you can wait until the very last minute to open the connection, which you do by calling IDbConnection.Open( ).

Once you’ve created the connection, you must specify what data you want to read. The IDbCommand interface represents a SQL command, and you can create an instance of it by calling IDbConnection.CreateCommand( ) or its constructor. You can create an IDbCommand before you call IDbConnection.Open( ).

Executing the IDbCommand is as simple as calling one of its execute methods. There are three:

  • IDbCommand.ExecuteNonQuery( ) is used to execute a SQL command that does not return any data, such as an insert, update, or delete statement.

  • IDbCommand.ExecuteScalar( ) is used to execute a SQL command that returns a single value, such as select count(*).

  • IDbCommand.ExecuteReader( ) is used to execute a SQL select command that returns a DataReader, which you can use to iterate over a number of rows and columns of resulting data.

The usage of the first two methods should be fairly obvious, but ExecuteReader( ) bears a little further explanation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.141.75