当前位置:网站首页>Use ado Net call stored procedure
Use ado Net call stored procedure
2022-06-24 18:40:00 【MousseIn】
ADO.NET Calling stored procedure
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 .
边栏推荐
- Is there a security risk in opening an account online? What to do if the business department opening an account nearby is far away from home. Is there any capital requirement for opening an account?
- [untitled]
- Millions of dollars worth of NFT were stolen in the attack, and Google issued an emergency warning to 3.2 billion users worldwide | February 21 global network security hotspot
- okcc呼叫中心数据操作的效率问题
- SAP license: ERP for supply chain management and Implementation
- Overall planning and construction method of digital transformation
- Interview algorithm - string question summary
- Why should state-owned enterprises accelerate the digital transformation
- Application service access configuration parameters
- Knowledge points in T-SQL
猜你喜欢

Vite+web3: referenceerror: process is not defined

How to use Fisher's least significant difference (LSD) in R

(Video + graphics) introduction to machine learning series - Chapter 11 support vector machines

JS pre parsing
Business based precipitation component = & gt; manage-table

Window object

Vite+web3:报错出现ReferenceError: process is not defined

He "painted" what a smart city should look like with his oars

DOM (document object model)

微服务系统设计——数据模型与系统架构设计
随机推荐
In depth learning of movement methods
Business leaders compete for CIO roles
Building MVC system based on three-tier structure
Redis series (3) - sentry highly available
Redis learning -- list of redis operations
696. count binary substring
Ultimate Guide: comprehensive analysis of log analysis architecture of Enterprise Cloud native PAAS platform
Digital transformation informatization data planning and technology planning
Gateway solves cross domain access
Top ten popular codeless testing tools
Business based precipitation component = & gt; manage-table
Why are more and more people studying for doctors? Isn't it more and more difficult to graduate a doctor?
Monotone stack template
JS deep understanding of scope
Usage of typedef enum (enumeration)
How to perform power regression in R
Three layer switching experiment
What is business intelligence (BI)?
Bigdecimalavoiddoubleconstructorrule: do not directly use the double variable as a parameter to construct BigDecimal
电源噪声分析