HI,
I have one hash table. In that i have multiple data. Now i want to send all data from hash table to sqlserver table. How can i achieve this? Can any body pls give me some solution.
Thanks & Regards,
Nagaraju P
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Satish BhatPosted Aug 11, 2011, 7:30 AM
string connectionString = "YOUR_CONNECTION_STRING";
// Your Hashtable with data
Hashtable myHashTable = new Hashtable();
myHashTable.Add("Key1", "Value1");
myHashTable.Add("Key2", "Value2");
myHashTable.Add("Key3", "Value3");
myHashTable.Add("Key4", "Value4");
myHashTable.Add("Key5", "Value5");
// Create a DataTable and copy data from your Hashtable
// Note: Replace the datatype with your datatype
DataTable myDataTable = new DataTable();
myDataTable.Columns.Add(new DataColumn("Key", typeof(string)));
myDataTable.Columns.Add(new DataColumn("Value", typeof(string)));
foreach (DictionaryEntry item in myHashTable)
{
DataRow myRow = myDataTable.NewRow();
myRow[0] = item.Key.ToString();
myRow[1] = item.Value.ToString();
myDataTable.Rows.Add(myRow);
}
// Open a connection to the database.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// Create the SqlBulkCopy object.
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
{
// Set the number of records updated in 1 batch
// In this case store all values at one go
bulkCopy.BatchSize = myDataTable.Rows.Count;
// Map the Source Column from DataTabel to the
// Destination Columns in SQL Server Table
// Note if the column positions in the source DataTable
// match the column positions in the destination table,
// there is no need to map columns.
bulkCopy.ColumnMappings.Add(0, 0);
bulkCopy.ColumnMappings.Add(1, 1);
bulkCopy.DestinationTableName = "YOUR_DESTINATION_TABLE_NAME";
try
{
// Write from the source to the destination.
bulkCopy.WriteToServer(myDataTable);
}
catch (Exception ex)
{
// Show error message
}
}
}