Updating table from datatable
-
I am trying to update a table from a datatable. The datatable is populated first from a text file and then I would like to get that data into a database datatable. However the code below does not work, part of it is I do not know how to associate the connection string to the data adapter. Also, is there anything else I need to do? Do I need to have separate Update, Insert, and Delete commands or is it possible to just call the Update command? ConnectToDb connection = new ConnectToDb().conn; //this returns a SqlConnection SqlDataAdapter da = new SqlDataAdapter(); da.Update(ds.Tables["TradeOrderFillsPre"]);
-
I am trying to update a table from a datatable. The datatable is populated first from a text file and then I would like to get that data into a database datatable. However the code below does not work, part of it is I do not know how to associate the connection string to the data adapter. Also, is there anything else I need to do? Do I need to have separate Update, Insert, and Delete commands or is it possible to just call the Update command? ConnectToDb connection = new ConnectToDb().conn; //this returns a SqlConnection SqlDataAdapter da = new SqlDataAdapter(); da.Update(ds.Tables["TradeOrderFillsPre"]);
Reading the table into a
DataTable
and adding that to aDataSet
is what I would recommend, but iterating over the list of values in the text file and using a simpleSqlCommand
withSqlParameter
s (so you declare the command one and parameterize it to simply change the values and callExecuteNonQuery
) would also be easy and more efficient. If you want to use theSqlDataAdapter
, you must at least have theSelectCommand
assigned to with aSqlCommand
for your SELECT statement. In order to insert, update, or delete rows, however, you must have theInsertCommand
,UpdateCommand
, andDeleteCommand
assigned on theSqlDataAdapter
. You can use theSqlCommandBuilder
with theSelectCommand
if the command is simple enough (i.e., JOINs and other advanced statements are not supported). Also, theSelectCommand
must be parameterized (see theSqlCommand.Parameters
property). See theSqlDataAdapter
class documentation in the .NET Framework SDK (installed by default with VS.NET, and available online from http://msdn.microsoft.com/netframework[^]) for more information and an example of how to use some of these classes.Microsoft MVP, Visual C# My Articles