SQL stored procedure in. net

Source: Internet
Author: User

◆ Standard component programming is allowed for Stored Procedures

◆ Fast execution of Stored Procedures

◆ Stored procedures can reduce network traffic

◆ Stored procedures can be fully utilized as a security mechanism
The author of this article will introduce it to you. NET database application stored procedures, and how to associate it with ADO.. Net sqldataadapter object, DataSet object, and so on. the overall performance of the. NET database application.

3. Create a simple stored procedure:

Here I will introduce how to use Visual Studio. NET ide To create a stored procedure. Use Visual Studio. net IDE is very easy and intuitive to create a stored procedure, as long as you direct to the pubs database in the server resource manager and expand nodes, you will find a variety of database objects including the Stored Procedure

Right-click the Stored Procedure node to bring up a menu that contains the command "Create a stored procedure. After a stored procedure is created, the following code template is displayed in the code editing window of IDE:

Create procedure DBO. storedprocedure1
/*
(
@ Parameter1 datatype = default value,
@ Parameter2 datatype output
)
*/
As
/* Set nocount on */
Return

The above code template conforms to the simplified syntax rules for creating a stored procedure. The complete syntax rules are as follows:

Create proc [edure] procedure_name [; number]
[{@ Parameter data_type}
[Varying] [= default] [Output]
] [,... N]
[
{Recompile | encryption | recompile, encryption}]
[For replication]
As SQL _statement [... n]

The meaning of each parameter is not described here. If you are interested, you can refer to the information about the SQL Server 2000 database management system.

Below I will give a brief introduction to each syntax component in this code template. Create procedure declares the creation of a stored procedure, followed by the name of the stored procedure .; /*...... */"Is the parameter of the stored procedure, which can include input and output parameters. The content after the as keyword is the main part of the stored procedure, which is any number and type of SQL statements contained in the stored procedure. The return keyword indicates that the stored procedure ends and an integer status value can be returned to the caller. Next we will create a simple stored procedure without parameters and use it:

Create procedure DBO. up_getpublisherinfo
As
Select pub_id, pub_name, city, state, Country
From publishers
Return

After creating the stored procedure, save it. After saving, the node corresponding to the stored procedure appears in the server resource manager. Note that the create keyword in the code editing window is changed to the alter keyword, which is used to change any existing stored procedure. To run the preceding stored procedure, click its node and choose "Run stored procedure" from the shortcut menu. The running result is as follows:

4. Create a stored procedure with parameters:

We have created a simple stored procedure without parameters. Many stored procedures with parameters are often used in actual applications. Stored Procedures with parameters are generally used to update or insert data. We can use the same operation method to create a stored procedure with parameters:

Create procedure DBO. up_updatepublisherinfo
(
@ Pub_id char (4 ),
@ Pub_name varchar (40 ),
@ City varchar (20 ),
@ State char (2 ),
@ Country varchar (30)
)
As
Update publishers
Set pub_name = @ pub_name, city = @ city, state = @ state,
Country = @ country
Where (pub_id = @ pub_id)
Return

In the above Code for creating a stored procedure, we add a; @ "sign before the name to declare the local variable-parameter of the stored procedure, and also declare the type of each parameter, determine the direction value of each parameter, that is, whether the parameter is input, output, input, output, or return value. You can call the stored procedure by using the corresponding stored procedure name and correct and valid parameters. In addition, you can use the output keyword to add output parameters to parameters. For more information, see the preceding syntax rules. Output parameters can be returned to the caller.

The above stored procedure can update the information of the corresponding publisher in the publishers table. You can click the node of the stored procedure and choose "Run stored procedure" from the shortcut menu to execute it. Once executed, a dialog box for entering publisher information is displayed in IDE (3 ). In this dialog box, enter the correct and valid update information. Note that the pub_id value must exist in the original table, and click OK to update the data.

5. Create a database application for a simple stored procedure:

The following describes how to use the stored procedure without parameters to create a database application. The sqldataadapter object and DataSet object in ADO. NET are also used. The sqldataadapter object serves as a bridge between the SQL Server database and the DataSet object. The sqldataadapter object contains two common methods: the fill () method and the update () method. The fill () method can obtain the corresponding data from the database and fill it into the DataSet object. The update () method, as its name implies, is used to update the dataset. Before calling the fill () method, we must set the selectcommand attribute of the sqldataadapter object, which is actually a sqlcommand object. The selectcommand attribute contains valid SQL statements, which can be obtained from the database and filled into the DataSet object.

First, we create a Windows Forms Application with the programming language C #. Create a new project in Visual Studio. NET and add a new publishers class to the project. This class encapsulates the business logic of connecting to the background database and obtaining dataset objects. The procedure is as follows:

1. Add the necessary namespace reference: using system. Data. sqlclient ;;

2. Add the following necessary variables to the class:

Private sqlconnection cnpubs ;;
Private sqlcommand implements pubs ;;
Private sqldataadapter dapubs ;;
Private dataset dspubs ;;

3. Complete the connection to the background database in the constructor of this class to obtain the business logic such as the sqldataadapter object:

Public Publishers ()
{
Try
{
// Create a database connection object
Cnpubs = new sqlconnection ("Server = localhost; Integrated
Security = true; database = pubs ");;
// Create a sqlcommand object and specify its command type as stored procedure
Export pubs = new sqlcommand ();;
Publish pubs. Connection = cnpubs ;;
Export pubs. commandtype = commandtype. storedprocedure ;;
Export pubs. commandtext = "up_getpublisherinfo ";;
// Create a sqldataadapter object and set its selectcommand attribute to the above sqlcommand object
Dapubs = new sqldataadapter ();;
Dapubs. selectcommand = publish pubs ;;
// Create a DataSet object
Dspubs = new dataset ();;
}
Catch (exception ){}
}

4. finally, a getpublisherinfo () method is provided for this class. This method fills the DataSet object with the sqldataadapter object and returns the filled DataSet object. The method is as follows (it is worth noting that: the sqldataadapter object implicitly opens the database connection and closes the connection after obtaining data. This means that the DataSet object works in non-connection mode. When you explicitly open a database connection and obtain data, the sqldataadapter object does not close the connection ):

Public dataset getpublisherinfo ()
{
// Call the fill () method of the sqldataadapter object and return the DataSet object
Dapubs. Fill (dspubs );;
Return dspubs ;;
}

After the publishers class is designed, we add a DataGrid Control to the main form and use it to display data in the DataSet object. First, add the following member variables to the main form class:

Private publishers pubs ;;
Private dataset Ds ;;

Then, modify the constructor of the main form class as follows:
Public form1 ()
{
//
// Required for Windows Form Designer support
//
Initializecomponent ();;
//
// Todo: add Any constructor code after initializecomponent calls
//
Pubs = new publishers ();;
DS = pubs. getpublisherinfo ();;
Datagrid1.datasource = Ds. Tables [0];
}

As soon as the application starts the DataGrid control of the main form, the corresponding data obtained from the pubs database using the stored procedure without parameters is displayed. The program runs as follows:

6. Create a database application with a stored procedure containing parameters:

We have created a stored procedure application without parameters. Next we will create a more complex database application. In actual database applications, we often need to obtain data and update, insert, or delete data. In this case, we need to use the stored procedure with parameters. When using the sqldataadapter object, we will call its update () method. The Update () method automatically performs operations based on the changes in each record in the able object in the DataSet object. The sqldataadapter object also contains attributes such as updatecommand, insertcommand, and deletecommand. These attributes are actually sqlcommand objects. The Update () method selects the corresponding Attribute Based on the operation type.

When using stored procedures with parameters to create database applications, we generally use the sqlparameter class, which encapsulates various attributes and methods related to SQL parameters. The attributes include parametername, sqldbtype, direction, size, value, sourcecolumn, and sourceversion. Among them, parametername, sqldbtype, direction, size and other attributes are used to match the parameters defined in the stored procedure. For example, the sqlparameter object defined below is used to match the; @ pub_id "parameter in the previously defined up_updatepublisherinfo stored procedure.

Sqlparameter updparam = new sqlparameter ("@ pub_id", sqldbtype. Char, 4 );;

In the above definition, although the direction attribute is not explicitly given, its default value is input, which meets our needs. If the direction attribute of a sqlparameter object is InputOutput, output, or returnvalue, the direction attribute must be explicitly stated, for example, the following code clearly states that the direction attribute of a sqlparameter object is output.

Oparam. Direction = parameterdirection. output ;;

The sourcecolumn attribute is used to match the datacolumn object in a able object. This matching can implicitly import the required sqlparameter object when the update () method is called to update the datatable object. If this attribute is not declared during definition, you must explicitly describe the sourcecolumn attribute of the sqlparameter object in the code.

The default value of the sourceversion attribute is the current value in the corresponding field of the datarow object, that is, the value to be updated to the database. Of course, the sourceversion attribute can also point to the original value in the corresponding field of the datarow object, that is, the initial value obtained from the database. In the database transaction processing system, data synchronization is very important. Next we will establish a storage process that can detect data synchronization.

Create procedure DBO. up_updatepublishername
(
@ Pub_id char (4 ),
@ Pub_name varchar (40 ),
@ Original_pub_name varchar (40)
)
As
If exists (select pub_id
From publishers
Where (pub_id = @ pub_id) and (pub_name = @ original_pub_name ))
Begin
Update publishers set pub_name = @ pub_name
Where (pub_id = @ pub_id)
End
Return

Next, we call the stored procedure in the above application to update the name of the publisher. First, improve the business logic class-publishers class on the basis of the original application:

1. Add a new sqlcommand object, which can be used as
The updatecommand attribute is used: Private sqlcommand cmdupdpubs ;;
2. Update the constructor Publishers () of this class and add the following content:
// Create another sqlcommand object that references the stored procedure for updating the publisher name
Cmdupdpubs = new sqlcommand ();;
Cmdupdpubs. Connection = cnpubs ;;
Cmdupdpubs. commandtype = commandtype. storedprocedure ;;
Cmdupdpubs. commandtext = "up_updatepublishername ";;
// Add necessary parameters for the above sqlcommand object
Cmdupdpubs. Parameters. Add ("@ pub_id", sqldbtype. Char, 4, "pub_id ");;
Cmdupdpubs. Parameters. Add ("@ pub_name ",
Sqldbtype. varchar, 40, "pub_name ");;
Sqlparameter updparam = new sqlparameter
("@ Original_pub_name", sqldbtype. varchar, 40, "pub_name ");;
Updparam. sourceversion = datarowversion. Original ;;
Cmdupdpubs. Parameters. Add (updparam );;
3. Specify the updatecommand attribute of the sqldataadapter object as the sqlcommand object defined above:
Dapubs. updatecommand = cmdupdpubs ;;
4. Add method updatepublishername ():
Public void updatepublishername (Dataset dschanges)
{
// Update all changes
Dapubs. Update (dschanges );;
}

After the business logic class of the application is complete, add a button named; update dataset "on the main form, and add the Event Response Function of this button as follows:

Private void button#click (Object sender, system. eventargs E)
{
If (Ds. haschanges ())
{
Pubs. updatepublishername (Ds. getchanges ());;
DS. Clear ();;
DS = pubs. getpublisherinfo ();;
}
}

So far, the application's business logic class and main form class have been updated, and the current application can update the relevant content in the database based on the user's switch. As shown in program 5, after updating the data, you can open the corresponding table in SQL Server and verify whether the data has been updated successfully.

VII. Summary:

This article introduces the basic knowledge of stored procedures and how to build data-driven applications in. NET database applications by combining sqldataadapter objects and dataset objects. In this article, we have applied two types of stored procedures: one is a simple stored procedure without parameters, and the other is a stored procedure with parameters, sqlparameter objects must also be used to call this type of stored procedure. At the same time, it is not difficult to find that the data update business logic is encapsulated in the storage process as a good design method, which can improve the manageability, scalability and database security of applications. Similarly, the business logic for inserting and deleting data can also be encapsulated in the stored procedure and used in applications in a similar way. Finally, I hope this article will help you a lot.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.