Using SqlDataAdapter to insert a row
Set the select command with a "0 = 1" filter and use an SqlCommandBuilder so that the insert command is automatically generated for you.
var sqlQuery = "select * from Customers where 0 = 1";
dataAdapter = new SqlDataAdapter(sqlQuery, conn);
dataSet = new DataSet();
dataAdapter.Fill(dataSet);
var newRow = dataSet.Tables["Customers"].NewRow();
newRow["CustomerID"] = 55;
dataSet.Tables["Customers"].Rows.Add(newRow);
new SqlCommandBuilder(dataAdapter);
dataAdapter.Update(dataSet);
Using an SQL Data Adapter to update and insert rows doesn't update (only inserts)
No, the DataAdapter
will just look at the DataRow's RowState property. If it's Added
the InsertCommand
will be executed, if it's Modified
the UpdateCommand
will be executed. You have to load this row into the table from the database first.
You can fill an empty DataTable
with a DataAdapter
and your SelectCommand
including two parameters. If the table is empty you can add the DataRow
manually, otherwise you can modify the rows with the updated values (if any) and call dataAdpater.Update(tempTestTable)
.
Here's an example (untested):
SqlDataAdapter dataAdpater = new SqlDataAdapter(
"SELECT temptesttableid, Age, Name FROM TempTestTable WHERE Name = @Name",
connection);
DataTable testTable = new DataTable();
// note that you should use an available csv-parser instead
foreach (string line in File.ReadAllLines(path))
{
string[] columns = line.Split(new char[]{'\t'}, StringSplitOptions.None);
if(columns.Length >= 2)
{
string name = columns[0].Trim();
string ageStr = columns[1].Trim();
int age;
if (int.TryParse(ageStr, out age))
{
dataAdpater.SelectCommand.Parameters.AddWithValue("@Name", name);
int rowsAdded = dataAdpater.Fill(testTable);
if (rowsAdded == 0)
{
testTable.Rows.Add(name, age);
}
else
{
// update values?
}
}
}
}
dataAdpater.Update(testTable);
Why won't this DataAdapter insert rows into the database?
Each DataTable
tracks the RowState
of its rows, so manually adding data in a loop works because they are all Added
(it has nothing to do with manually creating the DataTable
- its the rows). When you load from some other source like Excel, they are not added/new.
If you use a DataAdapter
to fill the table, you can tell it not to set the RowState
to Unchanged. This is very useful for migrating data from one data store to another:
myDA.AcceptChangesDuringFill = False
...
rows = myDA.Fill(xlDT)
Cannot Add a Row Using SQL and CommandBuilder C#
Change the line with the error to this:
dataSet.Tables["CT_DETIMP"].Rows.Add(impRow);
Can not Insert into Database with SqlDataAdapter and MSSqlServer in c#
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.
Cannot Add new row to database with DataAdapter.insertCommand vb.net
I'm all in favor of using what works and I see the solution above works. The advantage of using a dataadapter however, is that it wraps all the sql commands needed for the CRUD operations of the datatable. You can configure your own commands or let visual studio configure them automatically by using a sqlcommandbuilder. Then once you have the adapter configured all you need to do is something like this
Dim myds As New DataSet()
Dim mytable as New datatable()
myds.Tables.Add(mytable)
Dim myconstr As String = "ConnectionStringtoDataBase"
Dim myconn As New SqlConnection(myconstr)
Dim da as new SqlDataAdapter( “SELECT * FROM StudentTable”,cnn)
Dim mycb As New SqlCommandBuilder(da)
da.Fill(mytable)
Dim myrow As DataRow = mytable.NewRow()
myrow("ID") = "thestudentid"
myrow("StudentName") = "John doe"
myrow("StudentID") = 12345
myrow("StudentClass") = "VB 101"
mytable.Rows.Add(myrow)
da.Update(mytable)
The CommandBuilder will automatically add insert, update and delete commands to the dataadapter (if your select command is one table only, otherwise you'll have to configure it manually).
DataAdapter Update not properly Inserting data into SQL Server?
Since you have called ticketReportDT.AcceptChanges() before updating database it is not going to update anything in the database.
Related Topics
Convert Datetime to Julian Date in C# (Tooadate Safe)
Does Garbage Collector Call Dispose()
How to Convert JSON Array to List of Objects in C#
Modifying a JSON File Using System.Text.JSON
Datagridview Using Sortablebindinglist
How to Create a Button That Can Send Keys to a Conrol Without Losing Focus - Virtual Keyboard
Send Email via C# Through Google Apps Account
View Post Request Body in Application Insights
C# - How to Determine Whether a Type Is a Number
How to Make the Xmlserializer Only Serialize Plain Xml
How to Optionally Turn Off the JSONignore Attribute at Runtime
Why Can't I Declare C# Methods Virtual and Static
Interesting "Params of Ref" Feature, Any Workarounds
Get the Final Generated HTML Source Using C# or Vb.Net
C# Dll Cannot Affect Value of a Number Passed by Reference from a Vb6 Application