简体   繁体   English

如何使用C#在SQL Server 2008中插入多个列表?

[英]How to insert multiple list in SQL Server 2008 using c#?

My table contains 10 columns. 我的表包含10列。 I need to insert a list using c#. 我需要使用c#插入列表。
I have stored the details of multiple members, for each count its has to insert the consecutive details in the same row. 我存储了多个成员的详细信息,对于每个计数,它必须在同一行中插入连续的详细信息。

  if (members.Count >= 1)

    {
         foreach (Members myList in members)
             {                             
            Command.Parameters.Add("first", SqlDbType.VarChar).Value = myList.first;
            Command.Parameters.Add("last", SqlDbType.VarChar).Value = myList.last;
            Command.Parameters.Add("age", SqlDbType.VarChar).Value = myList.age;
             }
    }

Example : for count=1 the table looks like "fName1","lName1",21 示例:对于count = 1,表看起来像“ fName1”,“ lName1”,21

for count=2 the table looks like "fName1","lName1",21,"fname2","lName2",21 对于count = 2,表看起来像“ fName1”,“ lName1”,21,“ fname2”,“ lName2”,21

please help on this. 请对此提供帮助。

The coding style looks ambiguous. 编码风格看起来模棱两可。 Your foreach loop runs for - 'Members' in members. 您的foreach循环运行-成员中的“成员”。 It makes hard to understand what are trying to do. 很难理解正在尝试做什么。 Let me suggest you to refactor your code and let the class name be 'Member'. 让我建议您重构代码并将类名设为“ Member”。 You can put members in db with ADO.Net (there are other ways too) as follows - 您可以使用ADO.Net将成员放入db中(还有其他方法),如下所示-

       using (SqlConnection connection = new SqlConnection(connectionString))
        {
            using (SqlCommand command = connection.CreateCommand())
            {
                //select just schema of the table.
                command.CommandText = "select * from members where 1=2;";
                using (SqlDataAdapter adapter = new SqlDataAdapter(command))
                {
                    using (SqlCommandBuilder builder = new SqlCommandBuilder(adapter))
                    {
                        using (DataTable dt = new DataTable())
                        {
                            foreach (Member item in memebers)
                            {
                                DataRow row = dt.NewRow();

                                row.SetField<string>("", item.FirstName);
                                row.SetField<string>("", item.LastName);
                                row.SetField<int>("", item.Age);
                                //
                                // number of SetField should be equal to number of selected columns.
                                //
                                dt.Rows.Add(row);
                            }
                            adapter.Update(dt);
                        }                         
                    }   
                }
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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