Click here to Skip to main content
15,892,480 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Suggest any way to send list values to SQL server?

like this,
List<int> iList = new List<int>();
iList.Add(2);
iList.Add(3);
iList.Add(5);
iList.Add(7);

I want to add values 2,3,5,7 to a column in Database.
Posted

 
Share this answer
 
It's a little complicated, if you mean you want to INSERT them as different row values.
It's pretty simple to do from a DataTable - just use SqlBulkCopy.WriteToServer[^] but there is no equivelant for a List<T>.
However, you could use this: Converting a List to a DataTable[^] or just use a DataTable to start with.
 
Share this answer
 
Why not simply loop the collection and insert the row on each loop. Something like
C#
using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection()) {
   try {
      connection.ConnectionString = connectionString;
      connection.Open();

      sql = "INSERT INTO MyTable (MyColumn) VALUES (@value)";
      using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(sql, connection)) {
         command.Parameters.Add(new System.Data.SqlClient.SqlParameter("@value", 
                                         System.Data.SqlDbType.Int));
         command.Prepare();

         foreach (int value in iList) {
            command.Parameters["@value"].Value = value;
            command.ExecuteNonQuery();
         }
      }
...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900