在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() + "\r\n"; } } return Info; }