我想在一个来自会话变量的表中插入一个值。我写的代码是:
protected void Button1_Click(object sender, EventArgs e)
{
double balance;
double reward;
if((double.TryParse(lblBalance.Text, out balance) && (double.TryParse(lblReward.Text, out reward))))
{
Session["FinalBalance"] = balance + reward;
}
else
{
// some kind of error handling
}
string CS = ConfigurationManager.ConnectionStrings["ABCD"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("Insert into tblRegister('Balance') values('@FinalBalance')", con);
cmd.Parameters.AddWithValue("@FinalBalance", Session["FinalBalance"].ToString());
}
}
但是当我点击提交按钮时,代码不会抛出任何异常并且不会插入需要的内容。这里有什么问题?
答案 0 :(得分:0)
您正在创建命令对象但不执行查询。您必须在Command对象上调用ExecuteNonQuery方法来插入记录。
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("Insert into tblRegister(Balance) values(@FinalBalance)", con);
cmd.Parameters.AddWithValue("@FinalBalance", Session["FinalBalance"].ToString());
cmd.ExecuteNonQuery ();
}