我有一个表,我想使用简单的更新命令更新。
protected void UpdateButton_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("UPDATE KPI_DETAILS_TABLE SET KPI1_Status =
@KPI1_Status, KPI2_Status = @KPI2_Status, KPI3_Status = @KPI3_Status,
KPI4_Status = @KPI4_Status, KPI5_Status = @KPI5_Status, KPI6_Status =
@KPI6_Status, Overall_Status= @Overall_Status WHERE TokenID = '" +
DropDownList1.SelectedItem.Text + "' AND TimeSet = '"
+ currentdate + "'", connection);
cmd.Parameters.AddWithValue("@KPI1_Status", DropboxKPI1.SelectedItem.Text);
cmd.Parameters.AddWithValue("@KPI2_Status", DropboxKPI2.SelectedItem.Text);
cmd.Parameters.AddWithValue("@KPI3_Status", DropboxKPI3.SelectedItem.Text);
cmd.Parameters.AddWithValue("@KPI4_Status", DropboxKPI4.SelectedItem.Text);
cmd.Parameters.AddWithValue("@KPI5_Status", DropboxKPI5.SelectedItem.Text);
cmd.Parameters.AddWithValue("@KPI6_Status", DropboxKPI6.SelectedItem.Text);
cmd.Parameters.AddWithValue("@Overall_Status", FinalStatus.SelectedItem.Text);
try
{
cmd.ExecuteNonQuery();
Error1.Text = "KPI Status Successfully Updated !!";
}
catch { Error1.Text = "Error during Updating status of KPIs"; }
finally { connection.Close(); }
}
然而,它抛出以下异常错误:
将varchar数据类型转换为日期时间数据类型会导致超出范围的值。
数据库中唯一的数据类型datetime
列是TimeSet
。但currentdate
也是数据类型datetime
。
DateTime currentdate = DateTime.Now.ToLocalTime();
那为什么会出现这个错误?请帮忙。
答案 0 :(得分:2)
a)使用WHERE
子句中的值以及SET
部分的值和
b)然后使用cmd.Parameters.AddWithValue("@TimeSet", DateTime.Now.ToLocalTime());
这也可以保护您免受SQL注入。
即。如果你有一个日期时间值,请尝试将其保留为日期时间值,并且不要试图在任何时候将其视为字符串。让ADO.Net和SQL Server处理任何必要的转换。
答案 1 :(得分:1)
您的代码应如下所示:
protected void UpdateButton_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("UPDATE KPI_DETAILS_TABLE SET"+
"KPI1_Status = @KPI1_Status, KPI2_Status = @KPI2_Status,"+
"KPI3_Status = @KPI3_Status, KPI4_Status = @KPI4_Status,"+
"KPI5_Status = @KPI5_Status, KPI6_Status = @KPI6_Status,"+
"Overall_Status= @Overall_Status"+
"WHERE TokenID = @ID AND TimeSet = @Time", connection);
cmd.Parameters.AddWithValue("@KPI1_Status", DropboxKPI1.SelectedItem.Text);
cmd.Parameters.AddWithValue("@KPI2_Status", DropboxKPI2.SelectedItem.Text);
cmd.Parameters.AddWithValue("@KPI3_Status", DropboxKPI3.SelectedItem.Text);
cmd.Parameters.AddWithValue("@KPI4_Status", DropboxKPI4.SelectedItem.Text);
cmd.Parameters.AddWithValue("@KPI5_Status", DropboxKPI5.SelectedItem.Text);
cmd.Parameters.AddWithValue("@KPI6_Status", DropboxKPI6.SelectedItem.Text);
cmd.Parameters.AddWithValue("@Overall_Status", FinalStatus.SelectedItem.Text);
cmd.Parameters.AddWithValue("@ID", DropDownList1.SelectedItem.Text);
cmd.Parameters.AddWithValue("@Time", DateTime.Now.ToLocalTime());
try
{
cmd.ExecuteNonQuery();
Error1.Text = "KPI Status Successfully Updated !!";
}
catch { Error1.Text = "Error during Updating status of KPIs"; }
finally { connection.Close(); }
}
SqlCommand
对象字符串中的混乱。SqlCommand
添加本地变量,而是添加了新的SqlParameters
,并定义了从(@ID,@ Time)获取值的位置。答案 2 :(得分:0)
相反,您使用DateTime.Now.ToString();
来提供Currentdate并重试。