Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
ASP .NET Database Programming Weekend Crash Course - J. Butler, T. Caudill.pdf
Скачиваний:
31
Добавлен:
24.05.2014
Размер:
3.32 Mб
Скачать

Session 19—Using DataReaders

189

Using DataReader Properties

OK, so now that you have your DataReader object, what can you do with it? Well, just like all other objects, the DataReader object has numerous properties and methods. We’ll start with the properties:

Item property

The Item property returns the value for a given column in its native format. In order to reference the value of a column, you need to pass a string representing the column name or an integer representing the column’s index. Take for example the following table called t_bands:

band_id

band_title

music_type_id

record_company_id

1

Hootie & The Blowfish

1

1

 

 

 

 

2

Toad the Wet Sprocket

1

1

 

 

 

 

You could reference the band_title field in either of the following ways:

oDR.Items(“band_title”) oDR.Items(1)

You’ll notice that we passed a one (1) to the DataReader object’s Items property. To clarify, the 1 is the column index or location of the column in the row from which we want to retrieve the data. We used 1 as the index, because the numbering of column indexes begins with 0.

FieldCount property

The FieldCount property, which is obviously read-only, returns the number fields, as an integer, in the current record. Here is some sample syntax for getting the FieldCount:

Dim iFCount As Integer iFCount = oDR.FieldCount

One possible application of the FieldCount property is to iterate through the columns in a DataReader and write out the column’s value as shown in Listing 19-2.

Listing 19-2 FieldCount property application

<%@ Page Language=”VB” %>

<%@ Import Namespace=”System.Data” %>

<%@ Import Namespace=”System.Data.OleDb” %> <SCRIPT LANGUAGE=”VB” RUNAT=”server”>

Sub Page_Load(Sender As Object, E As EventArgs) Dim oConn As OleDbConnection

Continued

190

Saturday Evening

Listing 19-2

Continued

Dim oCmd As OleDbCommand

Dim oDR As OleDbDataReader

Dim iFieldCount As Integer

Dim x As Integer

oConn = New OleDbConnection(“Provider=SQLOLEDB;Data

Source=(local);Initial Catalog=Music;User ID=music;Password=music”)

oConn.Open()

oCmd = New OleDbCommand() oCmd.Connection = oConn oCmd.CommandType = CommandType.Text

oCmd.CommandText = “SELECT * FROM t_bands” oDR = oCmd.ExecuteReader()

iFieldCount = oDR.FieldCount

While oDR.Read()

Dim oRow As New TableRow() For x = 0 To (iFieldCount - 1)

Dim oCell As New TableCell() oCell.Text = oDR.Item(x) oRow.Cells.Add(oCell)

Next tblExample.Rows.Add(oRow)

End While

oDR.Close

oConn.Close End Sub </SCRIPT> <HTML> <BODY>

<asp:Table ID=”tblExample” BorderWidth=1 GridLines=”both” Runat=”server”/> </BODY>

</HTML>

In Listing19-2, all we’ve done is open our OleDbDataReader object, obtain the number of fields in the DataReader using the FieldCount property, and iterate through the rows of the DataReader using the Read method. (We discuss the Read method later in this session.) For each row, we loop through the fields and create a table cell containing the columns’ value. Simple!

IsClosed property

The IsClosed method returns a Boolean value indicating whether the DataReader is closed. A value of true means that the DataReader is closed.

Session 19—Using DataReaders

191

RecordsAffected property

The RecordsAffected property returns the number of rows that are changed, inserted, or deleted by the Command object that opens the DataReader. 0 is returned from the RecordsAffected property if no records were affected by the command object, and –1 is returned for SELECT commands. The RecordsAffected property is not set until the

DataReader object is closed. The isClosed and RecordsAffected are the only DataReader properties that can be accessed after the DataReader has been closed.

Listing 19-3 illustrates how you can use the isClosed and RecordsAffected properties to display information about the Command that was executed to create a DataReader object.

Listing 19-3 Displaying command information

<%@ Page Language=”VB” %>

<%@ Import Namespace=”System.Data” %>

<%@ Import Namespace=”System.Data.OleDb” %> <SCRIPT LANGUAGE=”VB” RUNAT=”server”>

Sub Page_Load(Sender As Object, E As EventArgs) Dim oConn As OleDbConnection

Dim oCmd As OleDbCommand

Dim oDR As OleDbDataReader

Dim oParam As OleDbParameter

Dim iBandID As Integer = 0

If Page.IsPostBack Then iBandID = lstBands.SelectedItem.Value

oConn = New OleDbConnection(“Provider=SQLOLEDB;Data

Source=(local);Initial Catalog=Music;User ID=music;Password=music”)

oConn.Open()

oCmd = New OleDbCommand() With oCmd

.Connection = oConn

.CommandType = CommandType.StoredProcedure

.CommandText = “prBandDelete” oParam = New OleDbParameter With oParam

.ParameterName = “BandID”

.OleDbType = OleDbType.Integer

.Value = iBandID End With

.Parameters.Add(oParam) Try

oDR = .ExecuteReader() lstBands.Items.Clear lstBands.Items.Add(New ListItem(“”,0))

While oDR.Read()

Continued

192

Saturday Evening

Listing 19-3

Continued

lstBands.Items.Add(New ListItem(oDR.Item(“band_title”),oDR.Item(“band_id”)))

End While

Catch err As Exception

Response.Write(“The following error occurred:<BR>” & err.Message & “<BR>”)

End Try End With

oDR.Close

oConn.Close

If oDR.isClosed Then

If oDR.RecordsAffected > 0 Then lblDeleted.Text = “You deleted “ & oDR.RecordsAffected & “ bands from the database.”

End If End Sub </SCRIPT> <HTML> <BODY>

<FORM ID=”frmBandDelete” Runat=”server”>

<asp:ListBox ID=”lstBands” Size=”1” AutoPostBack=”true” Runat=”server”/> <BR/><BR/>

<asp:Label ID=”lblDeleted” Text=”” ForeColor=”Red” Runat=”server”/> </FORM>

</BODY>

</HTML>

You’ll notice that Listing 19-3 uses a ListBox Web Control, lstBands, to allow a user to select a band that he or she would like to delete from the t_bands table. When the Web Form containing lstBands is submitted, the id of the band is gathered and passed to

OleDbCommand, oCmd, as an OleDbParameter, oParam. The prBandDelete stored procedure, which deletes the selected band and returns a recordset containing the remaining bands, is then executed by calling the Command object’s ExecuteReader method. Following is the code for the prBandDelete stored procedure.

CREATE PROCEDURE prBandDelete @BandID INT = 0

AS

IF @iBandID > 0 BEGIN

DELETE FROM t_songs WHERE album_id IN (SELECT album_id FROM t_albums WHERE band_id = @iBandID)

DELETE FROM t_albums WHERE band_id = @iBandID DELETE FROM t_band_members WHERE band_id = @iBandID DELETE FROM t_bands WHERE band_id = @iBandID

END

SELECT

band_id, band_title