C# Access DB Update Query doesn't execute though it acts like it did

C# Access DB Update Query doesnt execute though it acts like it did

我这辈子都无法让这个更新查询正常工作。

弹出消息框说它已更新,但当我查看时,它没有!这是这三个字段中数据的示例:

Syslink = {EF45612D-6321-4D19-97A5-C9497D60D628}
CMCID = 44061
SEC_ID = {00EADB9A-6158-4D2B-85E4-E381CCB02611}

列的顺序如下:SEC_ID、SYSLINK、CMCID。 在访问的设计视图中,所有这三个字段都是 "Number" 数据类型,尽管从我在 Whosebug 上看到的情况来看,这在使用 AddWithValue 时并不重要,除非我误解了。

private void buttonMove_Click(object sender, EventArgs e)
{
    try
    {
        bredConn.Open();
        OleDbCommand cmd = new OleDbCommand();
        cmd.Connection = bredConn;
        cmd.CommandText = "UPDATE Component_Section SET [SEC_SYS_COMP_ID]='@Syslink',[SEC_CMC_LINK]='@Cmcid' WHERE [SEC_ID]='@Secid'";
        cmd.Parameters.AddWithValue("@Syslink", labelDebugDestinationSYSLink.Text);
        cmd.Parameters.AddWithValue("@Cmcid", labelDebugDestinationCMC.Text);
        cmd.Parameters.AddWithValue("@Secid", labelDebugSourceSECID.Text);
        cmd.ExecuteNonQuery();
        bredConn.Close();
        MessageBox.Show("Moved", "It moved", MessageBoxButtons.OK);
    }
    catch (Exception ex)
    {

        MessageBox.Show(ex.Message, "Error: On Move", MessageBoxButtons.OK, MessageBoxIcon.Error);
        bredConn.Close();
    }
}

首先,我总是避免使用 AddWithValue large number of reasons 我不会深入。

到目前为止,我发现代码有两个明显的问题。

  1. 由于 AddWithValue,正在推断每个参数的 OleDbParameter 类型。请改用 Add 并确保指定与数据库类型匹配的正确类型。

  2. 在查询字符串中使用单引号将参数括起来,例如 '@Syslink'。这充其量是不必要的(OleDbParameter 会自动处理)并且在最坏的情况下会中断,因为它主要用于字符串比较。

进行这些更改会带来额外的好处,即您的 Text 字段可以转换为正确的类型。

关于您当前的行为,查询是 运行(否则会抛出异常)但 WHERE 过滤器无法匹配您期望的行。

进行上述更改,然后重试。