ADO.NET调用存储过程
使用存储过程
存储过程有两点优点:
- 性能高
- 安全性好
在ADO.NET中调用存储过程
SqlCommand cmd = new SqlCommand();
cmd.CommandText ="sp_update_student";
cmd.CommendType = CommandType.StoredProcedure;
//...定义和添加SqlParameter参数
//...打开链接并执行命令
其中CommandText是负责讲存储过程名成包装成字符串发送给数据库,但是数据库只是默认String为sql语句。会报错,所以要设置CommendType属性。
例子上文将CommendType定义为: StoredProcedure,也就是存储过程属性,否则会报错,因为数据库不认识之前传的字符串。
在程序中会有三种形式传递sql语句:
- 执行拼接的sql语句
- 执行参数化sql语句
- 执行存储过程
其中执行存储过程的性能远高于其他两种性能,第二是参数化,最后一名是拼接sql语句
但是存储过程的安全性不是绝对的,参数化同样相对于拼接的sql语句有更好的安全性。
SqlCommand cmd = new sqlCommand()
cmd.Connection = conn;
cmd.CommandText ="sp_update_student";
cmd.CommandType = CommandType.StoreProcedure;
SqlParameter[] pars =
{
new SqlParameter("@name","zs")//输入参数
new SqlParameter("@result",null)//输出参数
};
pars[1].Direction = ParameterDirection.Output;
调用带参存储过程,获取输出参数值
- 获取输出参数的值时,应确保链接对象已关闭。
int count = convert.ToInt32(pars[1].Value);
例子如下
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;