Search code examples
c#sql-serverdataadapter

Can not Insert into Database with SqlDataAdapter and MSSqlServer in c#


I want to insert new record into the DataTable with DataAdapter. There are 2 columns in Person table. FirstName and LastName.
I have a code like below.

SqlConnection connection;
DataSet dsPerson;
SqlDataAdapter adapter;
string connectionString = Properties.Resources.ConnectionString;
connection = new SqlConnection(connectionString);

dsPerson = new DataSet("PersonDataSet");
adapter = new SqlDataAdapter();
SqlCommand selectCommand = new SqlCommand("SELECT * FROM Person", connection);
adapter.SelectCommand = selectCommand;
adapter.Fill(dsPerson, "Person");

string insertQuery = "INSERT INTO Person(FirstName, LastName) VALUES (@FirstName, @LastName)";
SqlCommand insertCommand = new SqlCommand(insertQuery, connection);

insertCommand.Parameters.Add(new SqlParameter("@FirstName", SqlDbType.NVarChar));
insertCommand.Parameters["@FirstName"].SourceVersion = DataRowVersion.Current;
insertCommand.Parameters["@FirstName"].SourceColumn = "FirstName";

insertCommand.Parameters.Add(new SqlParameter("@LastName", SqlDbType.NVarChar));
insertCommand.Parameters["@LastName"].SourceVersion = DataRowVersion.Current;
insertCommand.Parameters["@LastName"].SourceColumn = "LastName";

adapter.InsertCommand = insertCommand;

But when I try to insert new Record into DataSet it appears in the DataSet. But it does not do insert new record into DataBase.
The Code for Insert is below.

connection.Open();
DataRow newRow = dsPerson.Tables["Person"].NewRow();
newRow["FirstName"] = "Joseph";
newRow["LastName"] = "Sword";
dsPerson.Tables["Person"].Rows.Add(newRow);
dsPerson.Tables["Person"].AcceptChanges();
dsPerson.AcceptChanges();
adapter.Update(dsPerson, "Person");
connection.Close();

I even try to trace queries sent to sql server With Express Profiler. And i saw that it does not send insert command to the database.
So what is the problem? How to solve it?
Thank you.


Solution

  • You should not call AcceptChanges methods of dataset and DataTable because DataAdapter.Update method affects only changed/added/deleted rows from datatable.

    But after calling AcceptChanges all your DataRows will have Unchanged state.

    See MSDN for reference about DataAdapter:

    When an application calls the Update method, the DataAdapter examines the RowState property, and executes the required INSERT, UPDATE, or DELETE statements iteratively for each row, based on the order of the indexes configured in the DataSet.