In program development, we often have to do is to access the database. Sometimes you invoke stored procedures and DTS, and here's an example to illustrate how to implement
The first part invokes the stored procedure (with the parameter and get the return value)
1. Call SQL Server stored procedures
If we have one of the following stored procedures, very simple implementation, but only two of the incoming value to do addition processing and then return
CREATE PROCEDURE AddMethoD
(
@returnvalue int OUTPUT, --返回结果
@Parameter_1 int, --参数一
@Parameter_2 int --参数二
)
AS
-----------------------------------------------
set @returnvalue = @Parameter_1 + @Parameter_2
RETURN @returnvalue
-------------------------------------------------
GO
The following is the code that calls this stored procedure in C #
private int testprocedure ()
{
System.Random rnd = new Random ();
String constr = "Data source=localhost;initial catalog=testdb;user id=sa;password=sa;connect timeout=3000";
SqlConnection conn = new SqlConnection (CONSTR);
Conn. Open ();
SqlCommand cmd = new SqlCommand ();
Cmd. Connection = conn;
Cmd.commandtext = "Addmethod";
Cmd.commandtype = CommandType.StoredProcedure;
//Parameter one
SqlParameter parameter_1 = new SqlParameter ("@Parameter_1", SqlDbType.Int);
Parameter_1.direction = ParameterDirection.Input;
Parameter_1.value = (int) (RND. Nextdouble () * 100);
//Parameter two
SqlParameter parameter_2 = new SqlParameter ("@Parameter_2", SqlDbType.Int);
Parameter_2.direction = ParameterDirection.Input;
Parameter_2.value = (int) (RND. Nextdouble () * 100);
//return value
SqlParameter returnvalue = new SqlParameter ("@returnValue", SqldbType.int);
Returnvalue.direction = ParameterDirection.Output;
Cmd. Parameters.Add (returnvalue);
Cmd. Parameters.Add (parameter_1);
Cmd. Parameters.Add (parameter_2);
Try
{
cmd. ExecuteNonQuery ();
}
Finally
{
Conn. Close ();
}
Return (int) returnvalue.value;
}