0

I want to use a dataadapter with a datatable to insert thousands of record into a 30-column sql table.

SqlDataAdapter adapter = new SqlDataAdapter();
DataTable table = new DataTable();
adapter.InsertCommand = new SqlCommand("INSERT INTO ...");
adapter.UpdateBatchSize = 1000;
DataRow r = null;
foreach(var entry in list) 
{
    r = table.NewRow();
    r["lastchange"] = entry.TryGet("LastChangeTime"); 
    // <- throws System.ArgumentException: Column does not belong to table
    ...
}

Is there any way to not manually define the schema of the datatable, but to read it from the table the insertions should take place in?

1

2 Answers 2

1

Define SelectCommand and apply Fill method to get data first. If you need only table schema just make the query which returns no rows.

SqlDataAdapter adapter = new SqlDataAdapter();
DataTable table = new DataTable();
adapter.SelectCommand = new SqlCommand("SELECT * FROM myTable WHERE 1=2");
adapter.Fill(table);
Sign up to request clarification or add additional context in comments.

9 Comments

DO NOT EVER DO THAT. I have seen this in real world and it was terrible performance disaster.
@MarekVitek, under circiumstances everything can cause a disaster. Can you be more specific, which line is dangerous?
Dangerous is getting data structure by running query against DB. You might think that your query is simple, then will come someone who thinks why not put it behind view and suddenly you find yourselves running query against view containing multiple joins and few conditions so even simple query will end up doing lot of work.
@MarekVitek, Yes, running this against complex view may be costly, but sure it's not OP's case as he says "insert into .. sql table.", and SqlDataAdapter implies it's MS sql-server.
@dellos, I am not C# programmer. But you might want to look at FillSchema . I believe it is what you are looking for.
|
-1

You can create/define dataset in your project and can use it in your subsequent operation wherever you need.

Have a look at below link showing how to add dataset to your project and add tables into it and also how to use data adapters with this dataset.

https://msdn.microsoft.com/en-us/library/04y282hb.aspx

https://msdn.microsoft.com/en-us/library/ms171919.aspx

https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/populating-a-dataset-from-a-dataadapter

I hope this will help you. :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.