度量快速开发平台-专业、快速的软件定制快开平台

标题: 接收sql语句的返回值 [打印本页]

作者: fteair    时间: 2020-6-9 14:51
标题: 接收sql语句的返回值
首先,简要介绍一下我们需要什么?
我们想在sql中用 try...catch,如果成功,就返回我们查询的值,如果失败就返回-1
所以有了以下sql语句(写在后台的)
  1. string myInsert = @"begin try
  2.                                             insert into dbo.Categories values(@categoryName);
  3.                                             set @result = (select @@identity id); //设置成功返回值,这儿是我们查询自增id
  4.                                         end try
  5.                                         begin catch
  6.                                             set @result = -1;//设置失败返回值-1
  7.                                         end catch";
复制代码
Sql语句已经写好,现在就是需要获取到这个@result,后台代码可以参考一下
  1. //定义一个数据库执行指令
  2.                     SqlCommand insertCommand = new SqlCommand(myInsert, myConnection);
  3.                     //添加集合
  4.                     insertCommand.Parameters.Add(new SqlParameter() { ParameterName = "categoryName", Value = catename});
  5.                     //获取到result返回值,主要是这个Output
  6.                     insertCommand.Parameters.Add("@result", SqlDbType.Int).Direction = ParameterDirection.Output;
  7.                     insertCommand.ExecuteNonQuery();
  8.             //这个DataConvert.ToInt32是自定义方法,是把查询到的object对象转换为int
  9.                     int result = DataConvert.ToInt32(insertCommand.Parameters["@result"].Value);
  10.                     if (result > 0) {
  11.                         categoryinfo.ID = result;
  12.                     }
复制代码



作者: caixuqad    时间: 2020-6-9 18:14

作者: fteair    时间: 2020-6-10 14:09
caixuqad 发表于 2017-8-9 18:14






欢迎光临 度量快速开发平台-专业、快速的软件定制快开平台 (http://bbs.delit.cn/) Powered by Discuz! X3.2