开发者

iterate an Ilist and insert to table

I've an IList with 5 items. I need to insert these, looping one by one, from the list to a SQL Server table using ado.net. I am using IReader(enterprise library)

How can I do this开发者_JS百科?


Consider your List: IList<Customer> foo;

Using LINQ To SQL

Create a LINQ To SQL datacontext, and it's something like this:

using (var db = new CustomerDataContext())
{
   db.Customer.InsertAllOnSubmit(foo);
   db.SubmitChanges();
}

Using Stored Procedures

using (var conn = new SqlConnection())
{        
     using (var cmd = new SqlCommand(conn))
     {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "InsertCustomer";

        foreach (Customer c in foo)
        {
             cmd.Parameters.Clear();
             cmd.Parameters.Add(new SqlParameter("@CustomerName", c.Name);

             conn.Open(dbConnString);
             cmd.ExecuteNonQuery();
             conn.Close();
        }
    }
}

This code is perhaps not copy/paste ready, perhaps a syntax/name/property problem somewhere there, but it's definitely a starting point using ADO.NET.


If basic sqlconnection class you are using then you can do as below:

IList<Record> records = new List<Record>();

  SqlConnection connection = new SqlConnection("Give connection string here");

  connection.Open();
  var insertCommand = connection.CreateCommand();

  foreach (var record in records)
  {
    insertCommand.CommandText = string.Format("Insert into table1 (field1, field2) values ({0}, {2})", record.field1,
                                              record.field2);
    insertCommand.ExecuteScalar();
  }

  connection.Close();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜