当前位置:网站首页>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 .
边栏推荐
- Interview algorithm - string question summary
- Common MySQL commands of installation free version
- congratulate! The first dragon lizard community annual outstanding contribution award is announced. Check it now
- [NLP] 3 papers on how Stanford team builds a better chat AI
- BOM(Browser Object Model)
- What is business intelligence (BI)?
- An analysis of the comments on the TV series Douban by procedural apes
- Seven strategies for successfully integrating digital transformation
- Recommend a distributed JVM monitoring tool, which is very practical!
- Creating a new MySQL user in Amazon RDS environment - creating a new MySQL user in Amazon RDS environment
猜你喜欢

Seven strategies for successfully integrating digital transformation

Mariana Trench, Facebook's open source code analysis tool

Analysis on the issue of raising the right of MSSQL in 2021 secondary vocational group network security competition in Shandong Province
![[NLP] 3 papers on how Stanford team builds a better chat AI](/img/f1/1c2ff31a728152395618800600df45.jpg)
[NLP] 3 papers on how Stanford team builds a better chat AI

110. balanced binary tree

Graph traversal (BFS and DFS) C language pure handwriting

【leetcode】838. Push domino (Analog)

JS string method

Microservice system design -- interface document management design

Vite+web3: referenceerror: process is not defined
随机推荐
Solve the problem that the MapReduce program console does not have log information warn please initialize the log4j system properly
Why should state-owned enterprises accelerate the digital transformation
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?
Huitongda officially landed at the Hong Kong Stock Exchange: the gross profit margin continued to decline, and the book value of several shareholders still suffered losses
Several key points for enterprises to pay attention to digital transformation
Network security database penetration of secondary vocational group in 2022
Microservice system design -- data model and system architecture design
Top ten popular codeless testing tools
Knowledge points in T-SQL
SAP license:sap s/4hana is the answer
如何在 R 中执行稳健回归
JS picture display and hiding cases
Analysis on the issue of raising the right of MSSQL in 2021 secondary vocational group network security competition in Shandong Province
"2022" plans to change jobs and raise salary. It is necessary to ask interview questions and answers - browser
Self taught C special data type
What is decision intelligence?
Wechat applet development - Implementation of rotation chart
Usage of typedef enum (enumeration)
Some knowledge of the beginning of 2022
Leetcode skimming questions - the 72nd biweekly match and 281 weekly match