简体   繁体   English

将行添加到DataTable时没有错误,但是该行未添加到数据库中

[英]I get no errors when adding a row to a DataTable, but the row is not added to the database

I am trying to add a row to a table in a PostgreSQL database using ODBC. 我正在尝试使用ODBC在PostgreSQL数据库中的表中添加一行。 Although no exceptions are thrown, the row is not being added to the table. 尽管不会引发任何异常,但是该行并未添加到表中。 Here is my code: 这是我的代码:

    void TestNewRow()
    {
        try
        {
            DataSet dataSet = new DataSet();
            OdbcDataAdapter adapter = new OdbcDataAdapter();
            adapter.SelectCommand =
                new OdbcCommand("select read_time from plant_genie.plc_values_by_tag", m_db.GetConnection());
            OdbcCommandBuilder builder =
                new OdbcCommandBuilder(adapter);

            adapter.Fill(dataSet);

            DataTable valuesTable = dataSet.Tables[0];
            DataRow newRow = valuesTable.NewRow();
            newRow["read_time"] = DateTime.Now;
            valuesTable.Rows.Add(newRow);
            valuesTable.AcceptChanges();
            dataSet.AcceptChanges();
            adapter.Update(dataSet);
        }
        catch (Exception ex)
        {
            int a = 1;
        }
    }

I have a breakpoint in the exception handler and another at the end of the function. 我在异常处理程序中有一个断点,在函数末尾有另一个断点。 The second breakpoint is hit but not the first, so no exception is being thrown. 命中了第二个断点,但没有命中第一个断点,因此不会引发异常。 I have triple-checked that I'm connecting to the correct database. 我已经三重检查了我正在连接到正确的数据库。 I don't think I should need two AcceptChanges() calls and an Update() call, but even with all of that overkill, I'm still not getting a new row in my table. 我不认为我需要两个AcceptChanges()调用和一个Update()调用,但是即使有所有这些过大的杀伤力,我的表仍然没有得到新的一行。 What am I doing wrong? 我究竟做错了什么?

I tried to find a duplicate of this question, but there are so many questions about adding rows that if there was a duplicate, it is being hidden. 我试图找到该问题的重复项,但是关于添加行的问题太多了,如果存在重复项,那么该行将被隐藏。

Thank you for your help. 谢谢您的帮助。

RobR ROBR

Calling AcceptChanges marks all changes as accepted (ie it resets the state of everything to Unmodified ), so no changes will be saved to the database. 调用AcceptChanges会将所有更改标记为已接受(即,它将所有状态重置为Unmodified ),因此不会将任何更改保存到数据库。 Remove this call to both the table and dataset and your changes should be saved. 删除对表和数据集的调用,您的更改应保存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM