C#调用存储过程
------------------------------ 准备工作 -----------------------------
命名空间 using System.Data.SqlClient
using System.Data;
声明据库连接SqlConnection
string connStr="Server=localhost;database=stuIMS;uid=sa;pwd=admin";
SqlConnection conn=new SqlConnection(connStr);
声明据库命令SqlCommand
SqlCommand myCommand=new SqlCommand("存储过程名",conn);
myCommand.CommandType=CommandType.StoredProcedure;
声明数据适配器SqlDataAdapter
SqlDataAdapter da = new SqlDataAdapter();
声明数据集DataSet
DataSet myds=new DataSet();
------------------------------ 正文 -----------------------------
1. 无参数存储过程
SqlConnection conn=new SqlConnection(“connectionString”);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand();
da.SelectCommand.Connection = conn;
da.SelectCommand.CommandText = "NameOfProcedure";
da.SelectCommand.CommandType = CommandType.StoredProcedure;
//执行
DataSet myds=new DataSet();
da.Fill(myds,"tableName");
2. 有参数存储过程
SqlConnection conn=new SqlConnection(“connectionString”);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand();
da.SelectCommand.Connection = conn;
da.SelectCommand.CommandText = "NameOfProcedure";
da.SelectCommand.CommandType = CommandType.StoredProcedure;
//设置参数
SqlParameter param = null;
//输入参数
param = new SqlParameter("@ParameterName", SqlDbType.DateTime);
param.Direction = ParameterDirection.Input;
param.Value = Convert.ToDateTime(inputdate); //转换为datatime
da.SelectCommand.Parameters.Add(param);
//输出参数
param = new SqlParameter("@ParameterName", SqlDbType.DateTime);
param.Direction = ParameterDirection.Output;
param.Value = Convert.ToDateTime(inputdate); //存储过程参数值;
da.SelectCommand.Parameters.Add(param);
//执行语句之后
DateTime dtTemp = (DateTime )da.SelectCommand.Parameters["@ParameterName"].Value;
//返回值 如何得到返回值,还是个问题
param = new SqlParameter("@ParameterName", SqlDbType.DateTime);
param.Direction = ParameterDirection.ReturnValue;
param.Value = Convert.ToDateTime(inputdate);
da.SelectCommand.Parameters.Add(param);
//执行
DataSet myds=new DataSet();
da.Fill(myds,"tableName");
参考文献
http://cgxcn.blog.163.com/blog/static/13231242200941441532441/