[英]Session Variable value are not storing into MS Sql Server Database
我正在使用兩個會話變量,並將會話變量分配給另一個變量,並且我顯示它從會話變量中正確獲取值,但是當我嘗試插入MS Sql Server數據庫時,該值未插入數據庫中。任何想法?
以下是我的代碼:
Session["selected"] = "apple";
Session["current"] = 1;
string mycategory = Session["selected"].ToString();
int myId = Convert.ToInt32(Session["current"]);
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO [Marking] VALUES (@photoid, @photocategoryjudge, @totalmarks)", con);
cmd.Parameters.Add("@photoid", SqlDbType.Int).Value = myId;
cmd.Parameters.Add("@photocategoryjudge", SqlDbType.VarChar).Value = mycategory;
cmd.Parameters.Add("@totalmarks", SqlDbType.Int).Value = totalMarks;
cmd.ExecuteNonQuery();
con.Close();
我沒有答案,但是我為您提供了一些簡單的步驟,這些步驟將幫助您進行調試,並且這些步驟的基礎是良好的編碼標准,並且可以用於將來的項目中,
首先要做的是實現異常處理,這可以通過try...catch...finally
塊來完成。 您將嘗試使用大部分實際SQL命令的代碼塊,並且如果引發錯誤,則將您帶入Catch塊。 將變量分配給Exception將允許您將鼠標懸停以查看詳細信息。 捕獲可以針對不同的條件進行堆疊,其中Exception是同類中的最后一個,它將捕獲所有類型的異常。 這有點像case
陳述,因為只有一個catch系列會觸發。 該塊的最后一部分是Final語句,它將在預期的命令完成或發生異常處理之后運行。
您沒有利用的是ExecuteNonQuery()
方法實際上具有一個返回值(int32),該值表示Sql語句的“ 受影響的行”值。 對於簡單的insert語句,應為1。如果這是一個update命令,則可以為0或更高,具體取決於有多少行或任何條件。 無論哪種方式,它總是等於或大於0。如果在編碼中有錯誤,我將如何為它分配一個負值,並且為每種類型的異常分配一個不同的值。
最后一件事是在帶有斷點的調試模式下運行代碼。 當您達到斷點時,請查看哪些變量具有哪些值。 這將有助於了解發生了什么錯誤(如果有)。 您可以檢查Sql語句,然后嘗試直接在SSMS中運行(如果這是錯誤源)。
祝好運
Session["selected"] = "apple";
Session["current"] = 1;
string mycategory = Session["selected"].ToString();
int myId = Convert.ToInt32(Session["current"]);
int ra; // ra = Rows Affected
try {
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO [Marking] VALUES (@photoid, @photocategoryjudge, @totalmarks)", con);
cmd.Parameters.Add("@photoid", SqlDbType.Int).Value = myId;
cmd.Parameters.Add("@photocategoryjudge", SqlDbType.VarChar).Value = mycategory;
cmd.Parameters.Add("@totalmarks", SqlDbType.Int).Value = totalMarks;
ra = cmd.ExecuteNonQuery();
}
catch (SqlException sx) {
ra = -2; // breakpoint here
// If you stop here, your SQL has an error. Hover on sx for detail
// Error handling routine
catch (Exception ex) {
ra = -1; // breakpoint here
// non-sql error block. Hover on ex for more info
// Error handling routine
}
finally {
con.Close();
}
int Results = ra; // breakpoint here
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.