当前位置:网站首页>Use ado Net call stored procedure

Use ado Net call stored procedure

2022-06-24 18:40:00 MousseIn

Using stored procedures

Stored procedures have two advantages :

  • High performance
  • Good safety

stay ADO.NET Calling stored procedure in

SqlCommand cmd = new SqlCommand();
cmd.CommandText ="sp_update_student";
cmd.CommendType = CommandType.StoredProcedure;
//... Define and add SqlParameter Parameters 
//... Open the link and execute the command 

among CommandText It is responsible for packaging the stored procedure name into a string and sending it to the database , But the database is only the default String by sql sentence . Will report a mistake , So set up CommendType attribute .
The example above will CommendType Defined as : StoredProcedure, That is, stored procedure properties , Otherwise, an error will be reported , Because the database does not recognize the string passed before .

There are three forms of transmission in the program sql sentence :

  • Performing spliced sql sentence
  • Perform parameterization sql sentence
  • Execute stored procedures

The performance of executing stored procedures is much higher than the other two , The second is parameterization , The last one is splicing sql sentence
But the security of stored procedures is not absolute , Parameterization is also relative to splicing sql Statement has better security .


SqlCommand cmd = new sqlCommand()
cmd.Connection = conn;
cmd.CommandText ="sp_update_student";
cmd.CommandType = CommandType.StoreProcedure;
SqlParameter[] pars =
{
    
new SqlParameter("@name","zs")// Input parameters 
new SqlParameter("@result",null)// Output parameters 
};
pars[1].Direction = ParameterDirection.Output;

Call a stored procedure with parameters , Get the output parameter value

  • When getting the value of the output parameter , Make sure that the linked object is closed .
int count = convert.ToInt32(pars[1].Value);     

Examples are as follows

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
namespace CH03
{
    
    class Program
    {
    
        static void Main(string[] args)
        {
    

            string conStr = "server=.;database=MySchool;uid=sa;pwd=123456";
            // Create database link 
            SqlConnection con = new SqlConnection(conStr);
           // establish SqlConnection Object to pass the database link string .

            con.Open();
            // Open database link 

            string sql = "proc_stuResultParam";
            // Create the incoming string , And pass in the stored procedure name .
            // Parameterized construction without parameters is unnecessary 
            SqlParameter[] par ={
    
                                new SqlParameter("@score",90),
                                new SqlParameter("@subject","java oop"),// Input parameters 
                                new SqlParameter("@count",0),// Output parameters ,null Provided by stored procedures 
                                new SqlParameter()// Leave the return value blank return
                                };
            // Pass in data as a parameterized array 
            par[2].Direction = ParameterDirection.Output;// use ParameterDirection Method to set the output parameter 
            par[3].Direction = ParameterDirection.ReturnValue;// use parameterDirection Method to set the return value 
           
            SqlCommand cmd = new SqlCommand(sql,con);// establish sqlCommand object 
            cmd.CommandType = CommandType.StoredProcedure;// The declaration is executed as a stored procedure .
            cmd.Parameters.AddRange(par);// take cmd The parameters in the and the stored procedure to be executed correspond to 
            
            using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))// Point out CommandReader And then call CommandBehavior.CloseConnetion Method to close the link 
            {
    
                while (reader.Read())
                {
    
                    Console.WriteLine(reader[0]+" "+reader[1]);
                }
            }// The value can only be obtained after the database link is broken .
            int count = Convert.ToInt32(par[2].Value);// Get the value of the stored procedure output parameter 
            int r = Convert.ToInt32(par[3].Value);// Get stored procedure return Return the value of the value 
            Console.WriteLine(" Output parameters :{0}",count);
            Console.WriteLine(" Return value :{0}",r);
            Console.ReadLine();
        }
    }
}

The stored procedure used is the stored procedure learned before proc_stuResultParam
If this is the case, call the data

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace CH03
{
    
    class Program
    {
    
        static void Main(string[] args)
        {
    

            string conStr = "server=.;database=MySchool;uid=sa;pwd=123456";
            // Create database link 
            SqlConnection con = new SqlConnection(conStr);
            // establish SqlConnection Object to pass the database link string .

            con.Open();
            // Open database link 

            string sql = "proc_stuResultParam";
            // Create the incoming string , And pass in the stored procedure name .
            // Parameterized construction without parameters is unnecessary 
            SqlParameter[] par ={
    
                                new SqlParameter("@score",90),
                                new SqlParameter("@subject","java oop"),// Input parameters 
                                new SqlParameter("@count",0),// Output parameters ,null Provided by stored procedures 
                                new SqlParameter()// Leave the return value blank return
                                };
            // Pass in data as a parameterized array 
            par[2].Direction = ParameterDirection.Output;// use ParameterDirection Method to set the output parameter 
            par[3].Direction = ParameterDirection.ReturnValue;// use parameterDirection Method to set the return value 

            SqlCommand cmd = new SqlCommand(sql, con);// establish sqlCommand object 
            cmd.CommandType = CommandType.StoredProcedure;// The declaration is executed as a stored procedure .
            cmd.Parameters.AddRange(par);// take cmd The parameters in the and the stored procedure to be executed correspond to 

            using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))// Point out CommandReader And then call CommandBehavior.CloseConnetion Method to close the link 
            {
    
                while (reader.Read())
                {
    
                    Console.WriteLine(reader[0] + " " + reader[1]);
                    int count = Convert.ToInt32(par[2].Value);// Get the value of the stored procedure output parameter 
                    int r = Convert.ToInt32(par[3].Value);// Get stored procedure return Return the value of the value 
                    Console.WriteLine(" Output parameters :{0}", count);
                    Console.WriteLine(" Return value :{0}", r);
                }
            }// The value can only be obtained after the database link is broken .
          
            Console.ReadLine();
        
        
        }
    }
}

In this case, the above three values can be taken , But the following return values and output parameters are not available , As mentioned above : When getting the value of the output parameter , Make sure that the linked object is closed .

原网站

版权声明
本文为[MousseIn]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202211332353806.html