How to save an arbitrary DataTable to a new SQL Table - c#

Suppose I have an ADO.NET DataTable that I was to 'persist' by saving it to a new table in a SQL Server database - is there a fast way of doing this?
I realise I could write code generating the DDL for the 'CREATE TABLE' statement by looping through the DataColumns collection and working out the right type mappings and so on ... but I'm wondering if there is an existing method to do this, or a framework someone has written?
(NB: I need to be able to handle arbitrary columns, nothing too fancy like blobs; just common column types like strings, numbers, guids and dates. The program won't know what the columns in the DataTable are until run-time so they can't be hard-coded.)

ADO.net cannot create tables in SQL Server directly, however, SMO can do this with the .Create method of the Table class. Unfortunately, there is no built-in way to use a DataTable to define an SMO Table object.
Fortunately, Nick Tompson wrote just such a DataTable-to-SMO.Table routine back in 2006. It is posted as one of the replies to this MSDN forums topic http://social.msdn.microsoft.com/forums/en-US/adodotnetdataproviders/thread/4929a0a8-0137-45f6-86e8-d11e220048c3/ (edit: I can make hyperlinks now).
Note also, the reply post that shows how to add SQLBulkCopy to it.

If the table exists, you can use SqlBulkCopy (which will accept a DataTable) to get the data into the table in the fastest possible way (much faster than via an adapter). I don't think it will create the table though. You might have to write the DDL yourself, or find some existing code to loop over the DataTable.Columns to do it.

I think this post can help

I might be easier to store your DataTable as XML. just create a table with an XML column.

Related

Updating multiple values to sql table using Datagridview in C#

I am having a SQL table cost(sno,comp_name,sellingprice).
I need to develop an interface for entering values of sellingprice, where sno and comp_name are static values.
I set default value for sellingprice as 1.
For this purpose I used a Datagridview by choosing datasource and then the COST table contents to be displayed in the Datagridview.
Finally if user enters/updates values in the sellingprice column, then the changes need to be reflected in the Database.
Can somebody please help me in achieving this..
Thanks in advance..!
There are many ways to achieve what you're asking for. The easiest way is using SqlDataAdapter class.
There are at least 2 known to me ways to create Update/Insert/.. commands:
automatic (Adapater generates SQL itself)
manual (You do it in a way you like it)
For concrete and complete example of different patterns for this object look on
How To Update a SQL Server Database by Using the SqlDataAdapter Object in Visual C# .NET

IS there a short way to insert dataset into a new MS Access table?

I'm consuming a 3rd-party web service that outputs a Dataset (from XML). I'd like to create a new table in my local MS Access database that contains the DataSet data.
Is there a simple way to hand-off the DataSet to a .net object and ask it to "create a table from this"?
I know that we can use different parts of ADO to extract schema, build commands, insert rows, etc. I figured there has to be a simpler way.
The only two ways I know of are to
Walk through the DataSet field by
field and generate a DDL instruction
(which is valid for MS-Access)
Add a reference to ADOX, create a new table (with columns) and append the new table to the ADOX catalog. More info here. But again you are walking throught the dataset table field by field.
I haven't provided much detail on either of these approaches since I don't think they match what you've specified.
It seems you are looking for a quicker way than either of those so I guess the answer to your question is no.

arraylist to a table

I have an arraylist called backuplist.
this arraylist has structures in it.
So what i need to do is transfer this arraylist in a table and then store this table in my SQL database.
Anybody with ideas as to what i should do..??
Even if it is a different way to do this please let me know.
Thanks
If you are using VS2008 (tags), you should ideally use List<T>, not ArrayList. You can convert from a List<T> to a DataTable like so; then just use a SqlDataAdapter or SqlBulkCopy to get the data into the database.
This isn't a complete solution, but I thought I'd point you in the right direction. The problem is I don't really know your application, and your experience is limited, so it's going to be a stab in the dark.
Anyway, here are a couple of resources to get you started:
Converting Custom Collections To and From DataTable
http://blog.lozanotek.com/archive/2007/05/09/Converting_Custom_Collections_To_and_From_DataTable.aspx
Inserting New Records into a Database
http://msdn.microsoft.com/en-us/library/ms233812(VS.80).aspx
I'd agree on using a strongly typed list as Marc suggested. Another option to getting those into the database would be to plow through with a foreach (on either your list or array), and use the structure properties as parameters to an insert stored procedure.
We do this all the time in our app, where we might have a List coming from a business component and being tossed to the data layer, where we'll loop through, do any necesary manipulation, then run our update SP on each row.
Let me know if you need a snippet.
-Bob
I've been using an ArrayList returned by MySQL so it's populated with column names and types etc.
ArrayList list = new ArrayList();
// Add Items to list
DataTable table = new DataTable();
table.Load(list);

Copying data from one DataTable to another

What is the fastest way of transferring few thousand rows of data from one DataTable to another? Would be great to see some sample code snippets.
Edit: I need to explain a bit more. There is a filtering condition for copying the rows. So, a plain Copy() will not work.
You can't copy the whole table, you need to copy one rows. From http://support.microsoft.com/kb/308909 (sample code if you follow the link)
"How to Copy DataRows Between DataTables
Before you use the ImportRow method, you must ensure that the target table has the identical structure as the source table. This sample uses the Clone method of DataTable class to copy the structure of the DataTable, including all DataTable schemas, relations, and constraints.
This sample uses the Products table that is included with the Microsoft SQL Server Northwind database. The first five rows are copied from the Products table to another table that is created in memory."
What is wrong with DataTable.Copy?
Copying rows to a table throws some flags at me. I've seen people try this before, and in every single case what they really wanted was a System.Data.DataView. You really should check to see if the RowFilter property will do what you need it to do.

Add record to SqlDataReader

Is there any way I can push a new record to SqlDataReader after i pull a table down? I have this piece of trash code that I need to modify, and this seems like the easiest way to do what I need. I understand that this should not be done, and if you have to do it there is something seriously wrong with your logic, but is there a way?
Easiest way from that point is to just manually create a command with a command string of an insert(parametized if not sanitized/clean data, best to do that anyways, but could make code bulkier). Code for that should be quite small, considering you already have everything else setup.
When you say "push a new record to"... do you mean you want to add a record to the results? Or do you mean you want to do an INSERT?
The INSERT cannot be done with a reader; however, you can do things with readers. Of course, it would be simpler to update the original query so that you UNION the data.
In particular: you can't create your own SqlDataReader, but you can create your own bespoke IDataReader implementation; this could wrap the SqlDataReader, simply proxying data from the inner SqlDataReader until the SqlDataReader.Read() method returns false - then you could swap to returning you own data, returning true until you have run out of data. Not trivial to implement (mainly because you need to implement a lot of methods to write your own IDataReader), but certainly not impossible.
SqlDataReaders are forward read only so I doubt you can add a record in (regardless of whether you have pulled the whole table down). In fact anything that inherits DbDataReader is forward read only.
I'm guessing you need to do some manipulation with the records. Maybe what you can do instead is use the SqlDataReader to fill a DataTable and put a new record into the DataTable. But then you'd need to change your code to juggle a DataTable.
You need to expand your question a bit,
If, for example, you need to walk through a million records and update a field on the same table while walking through the data.
You can create a second SqlConnection to your db and execute update statements on the table (prone to locking issues), or better still insert all your changes into a temp table and merge the changes back into the original table after you are done with the reader.
There is little question I am tempted to ask, can this piece of logic be replaced with a single SQL UPDATE statement?

Categories

Resources