【问题标题】:Update command dont work ms access c#更新命令不起作用 ms 访问 c#
【发布时间】:2017-09-10 04:24:34
【问题描述】:

我有一个网格视图,它连接到从那里获取值的数据源。我创建了一个 selectedindexchanged 函数以在单击选择时工作。它显示 ID、orderID、From、To 和 Price 值并打开具有 4 个文本框和如果用户想要更改这些值,则为下拉列表。直到这里一切都很好。当用户更改一些值并单击提交时,数据库中没有任何更改。我使用 id 得到了值; " 字符串 id = orderGrid.SelectedRow.Cells[1].Text;"

这是我的提交按钮代码;

protected void submitButton_Click(object sender, EventArgs e)
    {      
        string id = orderGrid.SelectedRow.Cells[1].Text;
        OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("db.mdb") + ";Persist Security Info=False");
        string query = "update ordersTable set orderID=@testID,fromLocation=@from,toLocation=@to,price=@price WHERE ID = @id ";
        OleDbCommand cmd = new OleDbCommand(query, con);
        cmd.Parameters.AddWithValue("@id", id);
        cmd.Parameters.AddWithValue("@testID", orderBox.Text);
        cmd.Parameters.AddWithValue("@from", fromText.Text);
        cmd.Parameters.AddWithValue("@to", toList.SelectedItem.Text);
        cmd.Parameters.AddWithValue("@price", priceBox.Text);
        try
        {        
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
            Response.Write("Edit Complete !");

        }
        catch (Exception ex)
        {
            Response.Write("Error : " + ex);
        }
        orderGrid.DataBind();
    }

id 字符串在我的 selectedindexchanged 函数中工作得非常好。

【问题讨论】:

  • 一方面,这不是 SQL。这是微软访问。所以你可能想从那里开始。
  • 对不起,我从 sql 开始,然后我的朋友建议使用 ms 访问项目,我卡在那里一会儿
  • 您是否使用调试器检查该方法是否被调用?
  • 是的,因为我收到“编辑完成”消息

标签: c# sql asp.net ms-access


【解决方案1】:

在 OleDb 中,参数是通过它们的位置而不是它们的名称来识别的。
您的参数占位符 @ID 是查询中的最后一个,但您将其添加为集合中的第一个。
这会导致您的 WHERE 条件完全错误
(你搜索一条ID等于priceBox内容的记录)

只需将插入的 ID 作为最后一个参数移动

cmd.Parameters.AddWithValue("@testID", orderBox.Text);
cmd.Parameters.AddWithValue("@from", fromText.Text);
cmd.Parameters.AddWithValue("@to", toList.SelectedItem.Text);
cmd.Parameters.AddWithValue("@price", priceBox.Text);
cmd.Parameters.AddWithValue("@id", id);

这是主要问题,但我可以看到另一个由您使用 AddWithValue 引起的问题。这是一个方便的捷径,但有时它会让您为此付出代价。
在您的情况下,您将字符串传递给 @price 参数,如果您的 price 字段是小数(应该是),那么数据库引擎将尝试转换从字符串到小数,如果小数分隔符不同,则数据库中的值错误。最好检查 priceBox 中的值并自己将其转换为小数。

看到Can we stop to use AddWithValue already

【讨论】:

  • 非常感谢,没想到这么简单
猜你喜欢
  • 2016-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-25
  • 1970-01-01
  • 2015-07-24
相关资源
最近更新 更多