Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

ASP .NET Web Developer s Guide - Mesbah Ahmed, Chris Garrett

.pdf
Скачиваний:
38
Добавлен:
24.05.2014
Размер:
7.32 Mб
Скачать

330 Chapter 7 • Introduction to ADO.NET: A Simple Address Book

Notice how we do not include single quotes? For numerical data we leave our single quotes off and just send the value.This is a very simple way to send parameters into a stored procedure. In the “Adding to a Database” exercise that follows, we explicitly create parameters and return values in them.This is called output parameters, and they are very useful in certain situations.

Adding to a Database: Exercise

Adding data to the database involves many of the same steps that we took to select the data. At the database level, the database engine will open the table, navigate to a new row, and put in your data.This is overly simplistic, but covers the highpoints.

We will use a stored procedure, but this time we will use an output parameter to return the new primary key value of our new record. In SQL Server this is done using the @@IDENTITY function. SQL Server will return the last identity value in your session.This is very important for consistency.We don’t want the ID of a record that another user committed right after we committed ours. Figure 7.18 (A and B) contains the text for the stored procedure; note the Output syntax in the parameter declaration:

Figure 7.18 (A and B) Statements for Inserting Records

Figure 7.18A T-SQL

CREATE PROC usp_tblAddress_ins(

 

@AdrsID

INT = NULL OUTPUT

,

@FName

varchar(50)

,

@LName

varchar(50)

,

@Phone

char(15)

,

@EMail

varchar(255)

,

@WebPage

varchar(255)

,

@Age

tinyint

,

@Comments

varchar(2000)

)

 

 

AS

 

 

INSERT INTO

[dbo].[tblAddress]([FName]

,[LName]

,[Phone]

,[EMail]

Continued

www.syngress.com

Introduction to ADO.NET: A Simple Address Book • Chapter 7

331

Figure 7.18A Continued

,[WebPage]

,[Age]

,[Comments])

VALUES( @FName

,@LName

,@Phone

,@EMail

,@WebPage

,@Age

,@Comments)

SET @AdrsID = @@IDENTITY

Figure 7.18B Inserting Records with Access

INSERT INTO [tblAddress]([FName]

,[LName]

,[Phone]

,[EMail]

,[WebPage]

,[Age]

,[Comments])

VALUES( <Replace with @FName>

,<Replace with @LName>

,<Replace with @Phone>

,<Replace with @Email>

,<Replace with @WebPage>

,<Replace with @Age>

,<Replace with @Comments>) SELECT @@IDENTITY

The syntax for inserting records is very simple:

INSERT <table name> (<columns>n) VALUES (<values>n)

www.syngress.com

332 Chapter 7 • Introduction to ADO.NET: A Simple Address Book

NOTE

For Access you have to select the @@IDENTITY and return this in a DataReader, or use the ExecuteScalar method to return a single value.

This results in one record being inserted. Notice how we do not specify the primary key in our field list or values list. Indecently, these two lists must match for count and data type, or else SQL Server will throw an error.

Calling the stored procedure from our DAL, we use the same Connection object, but the Add method is quite different from our earlier code. Specifically, we are creating parameters and adding them to the parameter collection of our Command object.The SqlCommand object and the OleDbCommand object both have a parameter collection, and the same methods for creating and adding them. Our Add function will take a parameter for each column except the primary key, and the method will return a value of type Int32.This is equivalent to the SQL Server data type of INT.They are both capable of holding values between negative 2,147,483,648, and positive 2,147,483,647.Those are plenty of available IDs for our contact list. Figure 7.19 (A and B) contains the code for the Add method of our DAL.

Figure 7.19 (A and B) Inserting Records Using a Command Object with Declared Parameters

Figure 7.19A C#.NET (cs\CDalAddress.cs)

public Int32

Add(string FName,

string

LName,

string

Phone,

string

EMail,

string

WebPage,

Int16 Age,

string

Comments)

{

SqlCommand oCmd; SqlParameter oParam; string strSQL; Int32 AdrsID;

Continued

www.syngress.com

Introduction to ADO.NET: A Simple Address Book • Chapter 7

333

Figure 7.19A Continued

strSQL = "usp_tblAddress_ins";

oCmd = new SqlCommand(strSQL, oConn); oCmd.CommandType = CommandType.StoredProcedure;

oParam = oCmd.Parameters.Add("@AdrsID", SqlDbType.Int, 4);

oParam.Direction = ParameterDirection.Output;

oCmd.Parameters.Add("@FName", SqlDbType.VarChar, 50).Value = FName;

oCmd.Parameters.Add("@LName", SqlDbType.VarChar, 50).Value = LName;

oCmd.Parameters.Add("@Phone", SqlDbType.VarChar, 15).Value = Phone;

oCmd.Parameters.Add("@EMail", SqlDbType.VarChar, 255).Value =

EMail;

oCmd.Parameters.Add("@WebPage", SqlDbType.VarChar, 255).Value =

WebPage;

oCmd.Parameters.Add("@Age", SqlDbType.TinyInt, 2).Value = Age;

oCmd.Parameters.Add("@Comments", SqlDbType.VarChar, 2000).Value =

Comments;

try

{

if (oConn.State == ConnectionState.Closed)

{

oConn.Open();

}

oCmd.ExecuteNonQuery();

AdrsID = (Int32)oCmd.Parameters["@AdrsID"].Value; return AdrsID;

}

catch (Exception oErr)

{

throw oErr;

}

}

www.syngress.com

334 Chapter 7 • Introduction to ADO.NET: A Simple Address Book

Figure 7.19B VB.NET (vb\CDalAddress.vb)

Public Function Add(ByVal FName As String, _

ByVal LName As String, _

ByVal Phone As String, _

ByVal EMail As String, _

ByVal WebPage As String, _

ByVal Age As String, _

ByVal Comments As String) As Int32

Dim oCmd As SqlCommand

Dim oParam As SqlParameter

Dim strSQL As String

Dim AdrsID As Int32

strSQL = "usp_tblAddress_ins"

oCmd = New SqlCommand(strSQL, oConn)

oCmd.CommandType = CommandType.StoredProcedure

oParam = oCmd.Parameters.Add("@AdrsID", SqlDbType.Int, 4)

oParam.Direction = ParameterDirection.Output

oCmd.Parameters.Add("@FName", SqlDbType.VarChar, 50).Value = FName

oCmd.Parameters.Add("@LName", SqlDbType.VarChar, 50).Value = LName

oCmd.Parameters.Add("@Phone", SqlDbType.VarChar, 15).Value = Phone

oCmd.Parameters.Add("@EMail", SqlDbType.VarChar, 255).Value = EMail

oCmd.Parameters.Add("@WebPage", SqlDbType.VarChar, 255).Value =

WebPage

oCmd.Parameters.Add("@Age", SqlDbType.TinyInt, 2).Value = Age

oCmd.Parameters.Add("@Comments", SqlDbType.VarChar, 2000).Value =

Comments

Try

If oConn.State = ConnectionState.Closed Then

oConn.Open()

End If oCmd.ExecuteNonQuery()

AdrsID = oCmd.Parameters("@AdrsID").Value

Return AdrsID

Catch oErr As Exception

Continued

www.syngress.com

Introduction to ADO.NET: A Simple Address Book • Chapter 7

335

Figure 7.19B Continued

Throw oErr

End Try

End Function

Notice how the first parameter was explicitly set to a parameter object, and then this object was used to set the direction of the parameter.Valid values are Output, Input (default), Input/Output, and ReturnValue.The return value is useful for integer data, and is generally used to tell the outcome of the procedure; using 0 for success and 1 for failure are common, but any integer is acceptable. Output parameters are much more useful. If you are only returning one row of data, it is more efficient to return a batch of output parameters than a single row of data.We can’t bind to it, but is more efficient from the database side of the application.

To get the value out of the parameter, we have to close the connection. By calling the ExecuteNonQuery method of the Command object, we effectively close the connection after execution, and we can then access our value from the parameter collection. Getting the value is no different than getting it out of any other collection. It is interesting to note that you must name your parameters the same as the Declaration of the stored procedure. It seems that Microsoft decided to use name parameters when they wrote the data access code.This gives us the option of setting them out of order.

Updating Data in a Database: Exercise

In addition to inserting new data, we will want the ability to update the data. Perhaps someone changes his or her phone number or moves. In our sample, we will update all the columns except for the primary key of our table.The syntax for creating the update statement is in Figure 7.20 (A, B, and C).The declaration of our stored procedure is very similar to the Add stored procedure, but we are not using an output parameter.

Figure 7.20 (A, B, and C) Updating Data

Figure 7.20A ANSI SQL (ANSI Is the Standard Which All RDBMS Databases Try to Implement)

UPDATE <table name>

SET <Column1 name> = <value1>,

Continued

www.syngress.com

336 Chapter 7 • Introduction to ADO.NET: A Simple Address Book

Figure 7.20A Continued

<Column2 name> = <value2>

WHERE <primary key> = <identifier>

Figure 7.20B T-SQL

CREATE PROC usp_tblAddress_upd(

 

@AdrsID

INT

,

@FName

varchar(50)

,

@LName

varchar(50)

,

@Phone

char(15)

,

@EMail

varchar(255)

,

@WebPage

varchar(255)

,

@Age

tinyint

,

@Comments

varchar(2000)

)

 

 

AS

 

 

UPDATE [dbo].[tblAddress]

SET [FName]

= @FName

,

[LName]

= @LName

,

[Phone]

= @Phone

,

[EMail]

= @EMail

,

[WebPage]

= @WebPage

,

[Age]

= @Age

,

[Comments]= @Comments

WHERE [AdrsID] = @AdrsID

Figure 7.20C Updating Data in Access

UPDATE [tblAddress]

SET [FName] = <Replace with @FName>

,

[LName]

= <Replace

with

@LName>

,

[Phone]

= <Replace

with

@Phone>

,

[EMail]

= <Replace

with

@Email>

,

[WebPage]

= <Replace

with

@WebPage>

Continued

www.syngress.com

Introduction to ADO.NET: A Simple Address Book • Chapter 7

337

Figure 7.20C Continued

, [Age]

= <Replace with @Age>

, [Comments]= <Replace with @Comments>

WHERE [AdrsID] = <Replace with @AdrsID>

Again, we will use the Command object with parameters.We are using the default direction of Input to send in the new data. Any values that were not changed will just be overwritten with the same data. Refer to Figure 7.21 (A and B) for the Update method of our DAL example.

Figure 7.21 (A and B) Updating Data Using a Stored Procedure

Figure 7.21A C#.NET (cs\CDalAddress.cs)

public void Update(Int32 AdrsID, string FName, string LName, string Phone, string EMail, string WebPage, Int16 Age, string Comments)

{

SqlConnection oConn; SqlCommand oCmd; SqlParameter oParam; string strSQL;

strSQL = "usp_tblAddress_upd";

oConn = new SqlConnection(strConStr); oCmd = new SqlCommand(strSQL, oConn);

oCmd.CommandType = CommandType.StoredProcedure;

oCmd.Parameters.Add("@AdrsID", SqlDbType.Int, 4).Value = AdrsID;

oCmd.Parameters.Add("@FName", SqlDbType.VarChar, 50).Value = FName;

oCmd.Parameters.Add("@LName", SqlDbType.VarChar, 50).Value = LName;

oCmd.Parameters.Add("@Phone", SqlDbType.VarChar, 15).Value = Phone;

oCmd.Parameters.Add("@EMail", SqlDbType.VarChar, 255).Value = EMail;

Continued

www.syngress.com

338 Chapter 7 • Introduction to ADO.NET: A Simple Address Book

Figure 7.21A Continued

oCmd.Parameters.Add("@WebPage", SqlDbType.VarChar, 255).Value = WebPage;

oCmd.Parameters.Add("@Age", SqlDbType.TinyInt, 2).Value = Age;

oCmd.Parameters.Add("@Comments", SqlDbType.VarChar, 2000).Value =

Comments;

try

{

if (oConn.State == ConnectionState.Closed)

{

oConn.Open();

}

oCmd.ExecuteNonQuery();

}

catch (Exception oErr)

{

throw oErr;

}

}

Figure 7.21B VB.NET (vb\CDalAddress.vb)

Public Function Update(ByVal AdrsID As Int32, _

ByVal FName As String, _

ByVal LName As String, _

ByVal Phone As String, _

ByVal EMail As String, _

ByVal WebPage As String, _

ByVal Age As String, _

ByVal Comments As String) As Int32

Dim oConn As SqlConnection

Dim oCmd As SqlCommand

Dim oParam As SqlParameter

Dim strSQL As String

strSQL = "usp_tblAddress_upd"

oConn = New SqlConnection(strConStr)

Continued

www.syngress.com

Introduction to ADO.NET: A Simple Address Book • Chapter 7

339

Figure 7.21B Continued

oCmd = New SqlCommand(strSQL, oConn)

oCmd.CommandType = CommandType.StoredProcedure

oCmd.Parameters.Add("@AdrsID", SqlDbType.Int, 4).Value = AdrsID

oCmd.Parameters.Add("@FName", SqlDbType.VarChar, 50).Value = FName

oCmd.Parameters.Add("@LName", SqlDbType.VarChar, 50).Value = LName

oCmd.Parameters.Add("@Phone", SqlDbType.VarChar, 15).Value = Phone

oCmd.Parameters.Add("@EMail", SqlDbType.VarChar, 255).Value = EMail

oCmd.Parameters.Add("@WebPage", SqlDbType.VarChar, 255).Value =

WebPage

oCmd.Parameters.Add("@Age", SqlDbType.TinyInt, 2).Value = Age

oCmd.Parameters.Add("@Comments", SqlDbType.VarChar, 2000).Value =

Comments

Try

If oConn.State = ConnectionState.Closed Then

oConn.Open()

End If oCmd.ExecuteNonQuery()

Catch oErr As Exception

Throw New Exception(oErr.ToString)

End Try

End Function

Notice the use of the SqlDbType enumeration for specifying our data types.The ExecuteNonQuery method is more efficient, since we are not returning any data.

Deleting from a Database: Exercise

To delete data from your database, you will use the Delete syntax with your primary key to delete just the row you specify.The syntax for the Delete statement is shown in Figure 7.22 (A, B, and C).

It is important to include the Where clause here, or you will end up deleting all the records in your table.The stored procedure will take one parameter, the primary key of record to delete.

www.syngress.com