我正在使用两个会话变量,我将会话变量分配给另一个变量,我显示它从会话变量中正确获取值但是当我尝试插入到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();
答案 0 :(得分:1)
我没有答案,但我有一些简单的步骤可以帮助您调试,其基础是良好的编码标准,可以在以后的项目中用于某些变体,强>
首先要做的是实现异常处理,这可以通过try...catch...finally
块来完成。您将尝试大多数实际SQL命令的代码块,如果出现错误,它将引导您进入 Catch 块。将变量分配给异常将允许您悬停以查看详细信息。捕获可以针对不同的条件进行堆叠,异常是其中的最后一种,它将捕获所有类型的异常。这有点像case
语句,只有一个catch系列会触发。该块的最后一部分是 Finally 语句,它将在预期命令完成或异常处理发生后运行。
您没有使用的是ExecuteNonQuery()
方法实际上有一个返回值(int32),它表示Sql语句的 Rows Affected 值。对于一个简单的插入语句,这应该是1.如果这是一个更新命令,它可以是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