关于VS调用存储过程

首先写一个存储过程,以方便调用

Use class //指定所要建的存储过程的数据库

go

Create procedure students

@name nvarchar(20)  //定义一个nvarchar型的参数,注意,用“@”修饰

as

select * from student where 姓名=@name   //完整的SQL语句,引用该参数

 

执行编译。

再新建一个方法如下:

public void select()

{

            SqlConnection con = new SqlConnection("server=.;database=librarydatabase;user id=sa;pwd=;");  //数据库连接字段

            SqlDataAdapter sda = new SqlDataAdapter("students", con);  //调用存储过程,和前一个例子不同,这里用SqlDataAdapter,省去了打开数据库连接!          

            //con.Open();  此句可以省去,因为执行SqlDataAdapter已经打开了连接了

            SqlParameter para0 = new SqlParameter("@name", "张三");  //给参数赋值,注意参数格式

            sda.SelectCommand.Parameters.Add(para0);   //添加参数值

            sda.SelectCommand.CommandType = CommandType.StoredProcedure;  //指定执行类型为存储过程

            try

            {

                DataSet ds = new DataSet();

                sda.Fill(ds,"table"); 

                foreach (DataRow therow in ds.Tables["table"].Rows)

                {

                    Addr = therow["家庭地址"].ToString().Trim();    //读取返回记录的相应字段,Addr必须先声明为string型才可以使用

                    Tel = therow["电话"].ToString().Trim();      //读取返回记录的相应字段

                }

                Console.WriteLine("家庭地址是:{0},所在系:{1}", password, quanxian);

                con.Close();  

                Console.ReadKey();                             

            }

            catch

            {

                Console.WriteLine("something is wrong");

                con.Close();  

            }

  }

posted @ 2010-11-02 20:34  Earloye  阅读(3802)  评论(0编辑  收藏  举报