2011-09-02 80 views
6

多个表我想知道是什么做的标准/最好的方法如下:将数据插入到网络形式

我在asp.net形式的Web应用程序,并使用C#

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

的字段有:

primarykey, animal, street, country 

形式允许多个动物,多条街道和每PrimaryKey的多个国家。所以当我有数据是这样的:

[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. 我应该使用什么控件才能让用户输入多个值?目前我只是使用文本框,并想用分号分隔条目,但这可能不是正确的方法。

+0

对于(1):您可以使用交易。看到这个答案︰http://stackoverflow.com/questions/2044467/how-to-update-two-tables-in-one-statement-in-sql-server-2005/2044520#2044520 –

回答

3

我想建议你利用新的多行INSERT语句在2008年使SQL,你可以只通过一个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 t作为参数。

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

+0

非常感谢,我会在哪里我会放置代码?在INSERTING活动中? –

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(); 
      } 
     } 
    } 
} 

有更复杂的解决方案,但这是一个简单的解决方案。

+0

美丽的答案我会尝试 –