Question

I am trying to add a row to a table in a PostgreSQL database using ODBC. 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. 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

Was it helpful?

Solution

Calling AcceptChanges marks all changes as accepted (i.e. it resets the state of everything to Unmodified), so no changes will be saved to the database. Remove this call to both the table and dataset and your changes should be saved.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top