简体   繁体   中英

Updating database table with dataset issues

im trying to update my database table with a dataset. I have a local excel file that can be edited and imported into a dataset. Then i want to use this dataset with the updated data to update my database table. This is my code:

public void UpdateDatabase(DataSet data, string tableName)
{
    string connectionString = ConfigurationManager.ConnectionStrings["TestDbOnBrie"].ConnectionString;
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        try
        {
            connection.Open();
            using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM dbo.TransportSchedule_Customer;", connection))
            {
                SqlCommand selectCmd = new SqlCommand("SELECT * FROM dbo.TransportSchedule_Customer", connection);
                adapter.SelectCommand = selectCmd;
                SqlCommand updateCmd = new SqlCommand("UPDATE dbo.TransportSchedule_Customer SET Alias=@Alias, DeliveryDays1=@DeliveryDays1, DeliveryHours1=@DeliveryHours1, DeliveryType1=@DeliveryType1, DeliveryDays2=@DeliveryDays2, DeliveryHours2=@DeliveryHours2, DeliveryType2=@DeliveryType2, DeliveryDays3=@DeliveryDays3, DeliveryHours3=@DeliveryHours3, DeliveryType3=@DeliveryType3,  DistanceToDealer=@DistanceToDealer WHERE AdrID=@AdrID AND CustID=@CustID", connection);
                SqlCommand insertCmd = new SqlCommand("INSERT INTO dbo.TransportSchedule_Customer (CustID, Alias, AdrID, DeliveryDays1, DeliveryHours1, DeliveryType1, DeliveryDays2, DeliveryHours2, DeliveryType2, DeliveryDays3, DeliveryHours3, DeliveryType3, DistanceToDealer)" +
                    "VALUES (@CustID, @Alias, @AdrID, @DeliveryDays1, @DeliveryHours1, @DeliveryType1, @DeliveryDays2, @DeliveryHours2, @DeliveryType2, @DeliveryDays3, @DeliveryHours3, @DeliveryType3, @DistanceToDealer)", connection);


                //insertCmd.Parameters.Add("@CustID", SqlDbType.VarChar, 50, "CustID");
                //insertCmd.Parameters.Add("@AdrID", SqlDbType.Int, 50, "AdrID");
                //insertCmd.Parameters.Add("@Alias", SqlDbType.VarChar, 50, "Alias");

                //insertCmd.Parameters.Add("@DeliveryDays1", SqlDbType.VarChar, 50, "DeliveryDays1");
                //insertCmd.Parameters.Add("@DeliveryHours1", SqlDbType.VarChar, 50, "DeliveryHours1");
                //insertCmd.Parameters.Add("@DeliveryType1", SqlDbType.VarChar, 50, "DeliveryType1");

                //insertCmd.Parameters.Add("@DeliveryDays2", SqlDbType.VarChar, 50, "DeliveryDays2");
                //insertCmd.Parameters.Add("@DeliveryHours2", SqlDbType.VarChar, 50, "DeliveryHours2");
                //insertCmd.Parameters.Add("@DeliveryType2", SqlDbType.VarChar, 50, "DeliveryType2");

                //insertCmd.Parameters.Add("@DeliveryDays3", SqlDbType.VarChar, 50, "DeliveryDays3");
                //insertCmd.Parameters.Add("@DeliveryHours3", SqlDbType.VarChar, 50, "DeliveryHours3");
                //insertCmd.Parameters.Add("@DeliveryType3", SqlDbType.VarChar, 50, "DeliveryType3");

                //insertCmd.Parameters.Add("@DistanceToDealer", SqlDbType.VarChar, 50, "DistanceToDealer");
                //adapter.InsertCommand = insertCmd;


                updateCmd.Parameters.Add("@CustID", SqlDbType.VarChar, 50, "CustID");
                updateCmd.Parameters.Add("@AdrID", SqlDbType.Int, 50, "AdrID");
                updateCmd.Parameters.Add("@Alias", SqlDbType.VarChar, 50, "Alias");

                updateCmd.Parameters.Add("@DeliveryDays1", SqlDbType.VarChar, 50, "DeliveryDays1");
                updateCmd.Parameters.Add("@DeliveryHours1", SqlDbType.VarChar, 50, "DeliveryHours1");
                updateCmd.Parameters.Add("@DeliveryType1", SqlDbType.VarChar, 50, "DeliveryType1");

                updateCmd.Parameters.Add("@DeliveryDays2", SqlDbType.VarChar, 50, "DeliveryDays2");
                updateCmd.Parameters.Add("@DeliveryHours2", SqlDbType.VarChar, 50, "DeliveryHours2");
                updateCmd.Parameters.Add("@DeliveryType2", SqlDbType.VarChar, 50, "DeliveryType2");

                updateCmd.Parameters.Add("@DeliveryDays3", SqlDbType.VarChar, 50, "DeliveryDays3");
                updateCmd.Parameters.Add("@DeliveryHours3", SqlDbType.VarChar, 50, "DeliveryHours3");
                updateCmd.Parameters.Add("@DeliveryType3", SqlDbType.VarChar, 50, "DeliveryType3");

                updateCmd.Parameters.Add("@DistanceToDealer", SqlDbType.VarChar, 50, "DistanceToDealer");
                adapter.UpdateCommand = updateCmd;


                adapter.Update(data, "1");
            }
        }
        catch (Exception exception)
        {
            Console.WriteLine("ERROR in UpdateDatabase() method. Error Message : " + exception.Message);
        }
        finally
        {
            if (connection.State == System.Data.ConnectionState.Open)
            {
                connection.Close();
            }
        }
    }
}

My problem is that when i ONLY use the update command i get this error:

Update requires a valid InsertCommand when passed DataRow collection with new rows.

When i use both the update command and the Insert command i get this error:

Violation of PRIMARY KEY constraint 'PK_TransportSchedule_Customer'. Cannot insert duplicate key in object 'dbo.TransportSchedule_Customer'.

I'm thinking that it thinks the dataset table-rows are new rows and has to be inserted, but they are actually not. The rows exist the database and ONLY some of them are updated.

doe's anyone have any ideas of what to do?

Well i found out how to do this myself. here is how my method turned out. And this works perfect. It only updates the rows that exists and has different data in the file Dataset and the Dataset from the database.

My Method:

 public void UpdateDatabase(DataSet data, string custID)
        {
            DataTable fromdatabase = new DataTable();
            DataTable fromFile = data.Tables[0];

            string connectionString = ConfigurationManager.ConnectionStrings["TestDbOnBrie"].ConnectionString;
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                try
                {
                    connection.Open();
                    string sqlCmd = "SELECT * FROM dbo.TransportSchedule_Customer WHERE CustID = '" + custID + "';";
                    SqlCommand command = new SqlCommand(sqlCmd, connection);
                    using (SqlCommand updateCmd = new SqlCommand("UPDATE dbo.TransportSchedule_Customer SET DeliveryDays1=@DeliveryDays1, DeliveryHours1=@DeliveryHours1, DeliveryType1=@DeliveryType1, DeliveryDays2=@DeliveryDays2, DeliveryHours2=@DeliveryHours2, DeliveryType2=@DeliveryType2, DeliveryDays3=@DeliveryDays3, DeliveryHours3=@DeliveryHours3, DeliveryType3=@DeliveryType3,  DistanceToDealer=@DistanceToDealer WHERE Alias=@Alias AND CustID=@CustID", connection))
                    {
                        using (SqlDataAdapter adapter = new SqlDataAdapter(command))
                        {
                            adapter.UpdateCommand = updateCmd;
                            adapter.Fill(fromdatabase);
                            updateCmd.Parameters.Add("@CustID", SqlDbType.VarChar, 50, "CustID");
                            updateCmd.Parameters.Add("@Alias", SqlDbType.VarChar, 50, "Alias");

                            updateCmd.Parameters.Add("@DeliveryDays1", SqlDbType.VarChar, 50, "DeliveryDays1");
                            updateCmd.Parameters.Add("@DeliveryHours1", SqlDbType.VarChar, 50, "DeliveryHours1");
                            updateCmd.Parameters.Add("@DeliveryType1", SqlDbType.VarChar, 50, "DeliveryType1");

                            updateCmd.Parameters.Add("@DeliveryDays2", SqlDbType.VarChar, 50, "DeliveryDays2");
                            updateCmd.Parameters.Add("@DeliveryHours2", SqlDbType.VarChar, 50, "DeliveryHours2");
                            updateCmd.Parameters.Add("@DeliveryType2", SqlDbType.VarChar, 50, "DeliveryType2");

                            updateCmd.Parameters.Add("@DeliveryDays3", SqlDbType.VarChar, 50, "DeliveryDays3");
                            updateCmd.Parameters.Add("@DeliveryHours3", SqlDbType.VarChar, 50, "DeliveryHours3");
                            updateCmd.Parameters.Add("@DeliveryType3", SqlDbType.VarChar, 50, "DeliveryType3");

                            updateCmd.Parameters.Add("@DistanceToDealer", SqlDbType.VarChar, 50, "DistanceToDealer");

                            for (int i = 0; i < fromdatabase.Rows.Count; i++)
                            {
                                int Resultcompare = 0;
                                Resultcompare += string.Compare(fromdatabase.Rows[i]["DeliveryDays1"].ToString(), fromFile.Rows[i]["DeliveryDays1"].ToString());
                                Resultcompare += string.Compare(fromdatabase.Rows[i]["DeliveryHours1"].ToString(), fromFile.Rows[i]["DeliveryHours1"].ToString());
                                Resultcompare += string.Compare(fromdatabase.Rows[i]["DeliveryType1"].ToString(), fromFile.Rows[i]["DeliveryType1"].ToString());

                                Resultcompare += string.Compare(fromdatabase.Rows[i]["DeliveryDays2"].ToString(), fromFile.Rows[i]["DeliveryDays2"].ToString());
                                Resultcompare += string.Compare(fromdatabase.Rows[i]["DeliveryHours2"].ToString(), fromFile.Rows[i]["DeliveryHours2"].ToString());
                                Resultcompare += string.Compare(fromdatabase.Rows[i]["DeliveryType2"].ToString(), fromFile.Rows[i]["DeliveryType2"].ToString());

                                Resultcompare += string.Compare(fromdatabase.Rows[i]["DeliveryDays3"].ToString(), fromFile.Rows[i]["DeliveryDays3"].ToString());
                                Resultcompare += string.Compare(fromdatabase.Rows[i]["DeliveryHours3"].ToString(), fromFile.Rows[i]["DeliveryHours3"].ToString());
                                Resultcompare += string.Compare(fromdatabase.Rows[i]["DeliveryType3"].ToString(), fromFile.Rows[i]["DeliveryType3"].ToString());


                                Resultcompare += string.Compare(fromdatabase.Rows[i]["DistanceToDealer"].ToString(), fromFile.Rows[i]["DistanceToDealer"].ToString());
                                if (Resultcompare == 0)
                                {

                                    //do nothing
                                }
                                else
                                {

                                    fromdatabase.Rows[i]["DeliveryDays1"] = fromFile.Rows[i]["DeliveryDays1"];
                                    fromdatabase.Rows[i]["DeliveryHours1"] = fromFile.Rows[i]["DeliveryHours1"];
                                    fromdatabase.Rows[i]["DeliveryType1"] = fromFile.Rows[i]["DeliveryType1"];

                                    fromdatabase.Rows[i]["DeliveryDays2"] = fromFile.Rows[i]["DeliveryDays2"];
                                    fromdatabase.Rows[i]["DeliveryHours2"] = fromFile.Rows[i]["DeliveryHours2"];
                                    fromdatabase.Rows[i]["DeliveryType2"] = fromFile.Rows[i]["DeliveryType2"];

                                    fromdatabase.Rows[i]["DeliveryDays3"] = fromFile.Rows[i]["DeliveryDays3"];
                                    fromdatabase.Rows[i]["DeliveryHours3"] = fromFile.Rows[i]["DeliveryHours3"];
                                    fromdatabase.Rows[i]["DeliveryType3"] = fromFile.Rows[i]["DeliveryType3"];

                                    fromdatabase.Rows[i]["DistanceToDealer"] = fromFile.Rows[i]["DistanceToDealer"];
                                    adapter.Update(fromdatabase);
                                }

                            }

                        }
                    }
                }
                catch (Exception exception)
                {
                    Console.WriteLine("ERROR in UpdateDatabase() method. Error Message : " + exception.Message);
                }
                finally
                {
                    if (connection.State == System.Data.ConnectionState.Open)
                    {
                        connection.Close();
                    }
                }
            }
        }

if u need help just comment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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