1. 程式人生 > >使用ADO.NET執行帶引數的Sql語句

使用ADO.NET執行帶引數的Sql語句

不帶引數的SQL語句

這裡寫圖片描述

過載通用Update方法

這裡寫圖片描述

  /// <summary>
        /// 執行增、刪、改 (帶引數的SQL語句)
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public static int Update(string sql,SqlParameter[] parameter)
        {
            SqlConnection conn = new
SqlConnection(connString); SqlCommand cmd = new SqlCommand(sql, conn); try { conn.Open(); cmd.Parameters.AddRange(parameter);//新增引數陣列 return cmd.ExecuteNonQuery(); } catch (Exception ex) { throw
ex; } finally { conn.Close(); } }

編寫帶引數的SQL語句

這裡寫圖片描述

  string sql = "insert into Students (StudentName,Age,Gender,Birthday,";
            sql += "CardNo,ClassId,StudentIdNo,PhoneNumber,StudentAddress,StuImage) ";
            sql += " Values(@StudentName
,@Age,@Gender,@Birthday,@CardNo,@ClassId,"
; sql += "@StudentIdNo,@PhoneNumber,@StudentAddress,@StuImage)"; //建立引數陣列 SqlParameter[] parameter = new SqlParameter[] { new SqlParameter("@StudentName",objStudent.StudentName), new SqlParameter("@Age",objStudent.Age), new SqlParameter("@Gender",objStudent.Gender), new SqlParameter("@Birthday",objStudent.Birthday), new SqlParameter("@CardNo",objStudent.CardNo), new SqlParameter("@ClassId",objStudent.ClassId), new SqlParameter("@StudentIdNo",objStudent.StudentIdNo), new SqlParameter("@PhoneNumber",objStudent.PhoneNumber), new SqlParameter("@StudentAddress",objStudent.StudentAddress), new SqlParameter("@StuImage",objStudent.StuImage) }; try { //呼叫帶引數方法 return SQLHelper.Update(sql,parameter); } catch (Exception ex) { throw new Exception("儲存資料出現問題" + ex.Message); }

除錯

這裡寫圖片描述

這裡寫圖片描述