gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:41:24 27 4
gpt4 key购买 nike

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

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

用户将数据输入到表单中并单击“插入”,它会将数据插入到 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. 我应该使用什么控件来允许用户输入多个值?目前我只是在使用文本框并考虑用分号分隔条目,但这可能不是正确的方法。

最佳答案

我想建议您利用 SQL 2008 中新的多行插入语句,这样您就可以像这样传递一个 sql 语句:

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

到您的 SqlCommand,但我不知道如何构建这样的语句,而不会冒成为 SQL 注入(inject)攻击受害者的风险。

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

enter image description here

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

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 t 作为参数。

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

关于c# - 使用 Web 表单将数据插入多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7288133/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com