当前位置:网站首页>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 .
边栏推荐
- Keep two decimal places
- 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?
- Considerations for it project demand analysis
- Knowledge points of 2022 system integration project management engineer examination: ITSS information technology service
- [JS Framework] Failed to execute the callback function:
- Business based precipitation component = & gt; manage-table
- 解决执行MapReduce程序控制台没有日志信息WARN Please initialize the log4j system properly
- Window object
- 云服务器类型怎么选,要考虑什么?
- Online sequence flow chart making tool
猜你喜欢

Three layer switching experiment

JS deep understanding of functions

Solve the problem that the MapReduce program console does not have log information warn please initialize the log4j system properly

SAP license: SAP s/4 Hana module function introduction

Eight digit

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

Vite+web3: referenceerror: process is not defined

JS pre parsing

BOM(Browser Object Model)

Ten excellent business process automation tools for small businesses
随机推荐
Why are more and more people studying for doctors? Isn't it more and more difficult to graduate a doctor?
Leetcode topic [array] -216- combined sum III
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
Recommend 14 commonly used test development tools
香港服务器租用错误可能导致严重后果
Executing SQL statements with parameterized commands
Uniapp wechat applet calls mobile map to navigate to the target point
Restful design method
MySQL basic commands
R中的指数回归
Leetcode skimming questions - the 72nd biweekly match and 281 weekly match
Crmeb multi merchant PC packaging tutorial
Skills of writing test cases efficiently
Wechat applet development - Implementation of rotation chart
Business leaders compete for CIO roles
Mariana Trench, Facebook's open source code analysis tool
JDBC writes Chinese garbled code to the database
UnityShader 世界坐标不随模型变化
variable
Digital transformation informatization data planning and technology planning