SqlCommand.ExecuteScalar()方法

  在SQL Sever数据库里面判断SQL语句的方式很多,例如

1.判断增删改的ExcuteNonQUery()方法,会在增删改成功之后返回数字

2.读取sql查询语句的内容使用SqlDataReader()方法

而SqlCommand.ExecuteScalar()方法的作用就是

执行查询,并返回查询所返回的结果集中第一行的第一列。忽略其他行或列,返回值为object类型

可以用来判断查询是否成功并进行相应的操作,例如:

       public static string GetLoginResult(string constr,string u,string p) {
             SqlConnection conn = new SqlConnection(constr);
             conn.Open();
             SqlCommand comm = new SqlCommand("select * from Admin where user_Name='"+u+"'and user_Pwd='"+p+"'", conn);
             string user_Name =comm.ExecuteScalar().ToString();

             if (user_Name ==u)
             {
                 isLogin = "YES";//记录用户登录的状态
                 user = u;       //记录用户名
                 pwd = p;        //记录密码
                 return "登录成功!";
             }
             else {
                 isLogin = "NO";
                 user = "";
                 pwd = "";
                 return "登录失败!";
             }
         }
   public string Display(SqlDataReader read)
        {
            string Info = "";
            while (read.Read())
            {
                for (int i = 0; i < read.FieldCount; i++)
                {
                    Info += read[i].ToString() + "
";

                }
            }
            return Info;
        }
原文地址:https://www.cnblogs.com/yunquan/p/7300126.html