简体   繁体   中英

Create DataTable Schema from SQL

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?

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);

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://docs.microsoft.com/en-us/dotnet/framework/data/adonet/populating-a-dataset-from-a-dataadapter

I hope this will help you. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM