使用Web表单将数据插入多个表

时间:2011-09-02 19:05:45

标签: c# asp.net sql database sql-server-2008

我想知道执行以下操作的标准/最佳方式是什么:

我在asp.net中有一个表单Web应用程序并使用C#

用户将数据输入到表单中并单击INSERT,它将数据插入4个不同的表中。

字段是:

primarykey, animal, street, country

表单允许多个动物,多个街道和每个主键的多个国家/地区。所以当我有这样的数据时:

[1],[rhino,cat,dog],[luigi st, paul st], [russia,israel]

我需要将它插入这样的表中:

table1:
1,rhino
1,cat
1,dog

table2:
1,luigi st
1, paul st

table3:
1,russia
1,israel

问题

  1. 我完全不知道如何做到这一点。如果我只有一个表和每个主键一组数据我会使用InsertQuery并以这种方式做,但由于它是多个表我不知道该怎么做??

  2. 我应该使用哪些控件来允许用户输入多个值?目前我只是使用文本框,并考虑用半冒号分隔条目,但这可能不是正确的方法。

2 个答案:

答案 0 :(得分:3)

我想建议你利用SQL 2008中新的multirow insert语句,这样你就可以像这样传递一个sql语句:

INSERT INTO table1(id,animal_name) values (1,cat),(1,dog),(1,horse)... 

对于你的SqlCommand但我不知道如何构建一个这样的语句,而不会冒成SQL注入攻击的受害者。

另一种方法是在sql数据库中定义数据表类型: enter image description here

enter image description here

然后在C#中构造一个与您的数据表类型定义匹配的DataTable:

DataTable t = new DataTable();
t.Columns.Add("id");
t.Columns.Add("animal_name");
foreach(var element in your animals_list)
{
   DaraRow r = t.NewRow();
   r.ItemArray = new object[] { element.id, element.animal_name };
   t.Rows.Add(r);
}

// Assumes connection is an open SqlConnection.
using (connection)
{
    // Define the INSERT-SELECT statement.
    string sqlInsert = "INSERT INTO dbo.table1 (id, animal_name) SELECT nc.id, nc.animal_name FROM @animals AS nc;"

    // Configure the command and parameter.
    SqlCommand insertCommand = new SqlCommand(sqlInsert, connection);
    SqlParameter tvpParam = insertCommand.Parameters.AddWithValue("@animals", t);
    tvpParam.SqlDbType = SqlDbType.Structured;
    tvpParam.TypeName = "dbo.AnimalTable";

    // Execute the command.
    insertCommand.ExecuteNonQuery();
}

Read more here

或者,如果您熟悉存储过程,与先前的建议相同,但让存储过程接收DataTable作为参数。

如果以上都不适合您,请从Connection对象创建一个SqlTranscation,并遍历每个数据集的每一行,在相应的表中插入记录,最后提交事务。 Example here.

答案 1 :(得分:2)

使用前端的复选框。有一个服务/存储库来保存用户数据。如下所示:

public void UpdateUserAnimals(Guid userId, string[] animals)
{
    using (SqlConnection conn = new SqlConnection("connectionstring..."))
    {
        using (SqlCommand cmd = new SqlCommand("Insert Into UserAnimals(UserId, Animals) values (@UserId, @Animal)"))
        {
            conn.Open();
            cmd.Parameters.AddWithValue("@UserId", userId);
            foreach(string animal in animals)
            {
                cmd.Parameters.AddWithValue("@Animal", animal);
                cmd.ExecuteNonQuery();
            }
        }
    }
}

有更复杂的解决方案,但这很简单。

相关问题