zoukankan      html  css  js  c++  java
  • 接收sql语句的返回值

    首先,简要介绍一下我们需要什么?

    我们想在sql中用 try...catch,如果成功,就返回我们查询的值,如果失败就返回-1

    所以有了以下sql语句(写在后台的)

                        string myInsert = @"begin try 
                                                insert into dbo.Categories values(@categoryName);
                                                set @result = (select @@identity id); //设置成功返回值,这儿是我们查询自增id
                                            end try 
                                            begin catch 
                                                set @result = -1;//设置失败返回值-1
                                            end catch";

    Sql语句已经写好,现在就是需要获取到这个@result,后台代码可以参考一下

                         //定义一个数据库执行指令
                        SqlCommand insertCommand = new SqlCommand(myInsert, myConnection);
                        //添加集合
                        insertCommand.Parameters.Add(new SqlParameter() { ParameterName = "categoryName", Value = catename});
                        //获取到result返回值,主要是这个Output
                        insertCommand.Parameters.Add("@result", SqlDbType.Int).Direction = ParameterDirection.Output;
                        insertCommand.ExecuteNonQuery();
                //这个DataConvert.ToInt32是自定义方法,是把查询到的object对象转换为int
    int result = DataConvert.ToInt32(insertCommand.Parameters["@result"].Value); if (result > 0) { categoryinfo.ID = result; }

    注:此篇随笔只供参考使用,而且也有很多小瑕疵,最主要的不是代码,逻辑才是最重要的。

  • 相关阅读:
    vbscript 过滤 特殊字符
    C#3.0新体验(五)Lambda表达式
    C#3.0新体验(三)对象与集合初始化器收
    C#3.0新体验(四)匿名类型
    郁闷啊
    9.15
    谈话是需要对手的
    中秋节啊
    照片
    回家的 感受
  • 原文地址:https://www.cnblogs.com/Joker37/p/7323890.html
Copyright © 2011-2022 走看看