sql資料庫中的using和ExecuteScalar()注意點
阿新 • • 發佈:2019-02-19
int r = (int)cmd.ExecuteScalar();//注意Object型別需強制轉換為int
1.當ExecuteScalar執行的是聚合函式的時候,返回的不可能是null,如果執行的sql語句不是聚合函式返回的有可能是null
2.using相當於try.......finally,會自動呼叫dispose方法,所以連線物件開啟後conn.open,不用再呼叫conn.colose
private bool CheckUserInputOldPwd(string oldpwd, int autoid) { string sql = string.Format("select count(*) from UserLogin where autoid = '{0}' and loginpwd = '{1}'", autoid, oldpwd);//注意學會這種寫法 string constr = "Data Source = S7LVYWSI0SBPKLU;Initial Catalog = User;Integrated Security = True"; using(SqlConnection con = new SqlConnection(constr)) { using(SqlCommand cmd = new SqlCommand(sql,con)) { con.Open(); int r = (int)cmd.ExecuteScalar();//注意Object型別需強制轉換為int return r>0; } } }