关于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();  

            }

  }

转载于:https://www.cnblogs.com/Earloye/archive/2010/11/02/1867522.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值