最近老是使用到存储过程,于是就写了个方法执行存储过程,感觉还可以就发上来大家一起看看,不知道还有没有什么更好的方法的:
- /// <summary>
- /// 返回值的存储过程的执行
- /// </summary>
- /// <param name="ProcedureName">存储过程的名称</param>
- /// <param name="myPara">存储过程中的参数</param>
- /// <returns>执行的结果</returns>
- public static bool ExecuteProcInt(string ProcedureName, params SqlParameter[] myPara)
- {
- using (SqlConnection conn = SqlConn())
- {
- SqlCommand myCommand = new SqlCommand(ProcedureName, conn);
- myCommand.CommandType = CommandType.StoredProcedure;
- foreach (SqlParameter s in myPara)
- {
- myCommand.Parameters.Add(s);
- }
- conn.Open();
- if ((int)myCommand.ExecuteScalar() > 0)
- {
- conn.Close();
- return true;
- }
- else
- {
- conn.Close();
- return false;
- }
- }
- }
- /// <summary>
- /// 存储过程的执行
- /// </summary>
- /// <param name="ProcedureName">存储过程的名称</param>
- /// <param name="myPara">存储过程中的参数</param>
- /// <returns>执行的结果</returns>
- public static bool ExecutePro(string ProcedureName, params SqlParameter[] myPara)
- {
- using (SqlConnection conn = SqlConn())
- {
- SqlCommand myCommand = new SqlCommand(ProcedureName,conn);
- myCommand.CommandType = CommandType.StoredProcedure;
- foreach (SqlParameter s in myPara)
- {
- myCommand.Parameters.Add(s);
- }
- try
- {
- conn.Open();
- myCommand.ExecuteNonQuery();
- return true;
- }
- catch
- {
- return false;
- }
- finally
- {
- conn.Close();
- }
- }
- }
- 在使用的时候:
-
- SqlParameter[] myParaName = new SqlParameter[] { new SqlParameter("@UserName", txtuid.Text) };
- SqlParameter[] myParaLogin = new SqlParameter[] { new SqlParameter("@UserName", txtuid.Text), new SqlParameter("@PassWord", txtpwd.Text) };
- if (Sql.ExecuteProcInt("CheckName", myParaName) != true)
- {
- ltuid.Text = "用户名不存在";
- }
- else
- {
- if (Sql.ExecuteProcInt("CheckLogin", myParaLogin) != true)
- {
- ltpwd.Text = "密码错误";
- }
- else
- {
- Response.Redirect("Main.aspx");
- }
- }
- 把存储过程的名称,存储过程中所定义的变量,还有变量的实际值传给函数就可以了啊!