猿问

数据库查询错误

谁帮我看看啊,这个老是返回值为-1,一调试,就叫我重启vs什么问题啊,急求帮助!!

  public int ValidateAdmin(string sql, string adminID,string adminPwd)
        {
            int i;
            try
            {
                this.openCon();
                this.cmd = new SqlCommand(sql, this.con);
                this.cmd.CommandType = CommandType.StoredProcedure;
                SqlParameter[] pars = new SqlParameter[] {
                    new SqlParameter("@AdminID", SqlDbType.VarChar,50),
                    new SqlParameter("@AdminPwd", SqlDbType.VarChar,50)
                };
                pars[0].Value = adminID;
                pars[1].Value = adminPwd;
                foreach (SqlParameter parameter in pars)
                {
                    this.cmd.Parameters.Add(parameter);
                }
                i = (int)this.cmd.ExecuteScalar();
            }
            catch
            {
                i = -1;
            }
            finally
            {
                this.closeCon();
            }
            return i;
        }

 

        public void openCon()
        {
            if (this.con == null)
            {
                this.con = new SqlConnection(this.strCon);
            }
            if (this.con.State.Equals(ConnectionState.Closed))
            {
                this.con.Open();
            }
        }

翻翻过去那场雪
浏览 715回答 9
9回答

尚方宝剑之说

判断一下   this.cmd.ExecuteScalar(); 是否为NULL,再做 i = (int)this.cmd.ExecuteScalar();转换。

千万里不及你

数据库查询出错了,跳入catch代码块了

慕姐8265434

@小柑: this.cmd = new SqlCommand(sql, this.con);  这个sql语句有没有错

莫回无

@┢┦偉: 没有错  我突然发现  this.cmd.ExecuteScalar()不为空   改成下面  能获得i=1   if (this.cmd.ExecuteScalar() != null)                {                    i = 1;//原来是i = (int)this.cmd.ExecuteScalar();                 }

跃然一笑

@小柑: 谢谢了  总算解决这个问题了

陪伴而非守候

@小柑: 不会有负值,0或>0

繁花如伊

如果返回不为空给返回值赋值,不是把this.cmd.ExecuteScalar()的值直接返回去,因为不知道会返回什么值
随时随地看视频慕课网APP

相关分类

SQL Server
我要回答