简体   繁体   English

C#-将包含关系数据表的数据集插入到SQL Server中

[英]C# - Inserting DataSet that contains relational DataTables into Sql Server

Hi I have a DataSet in C# which contains 3 DataTables. 嗨,我在C#中有一个数据集,其中包含3个数据表。 Two of the tables: SummaryLocal_Bands and SummaryLocal_Averages contain an fk relationship to the pk in the 3rd table: SummaryLocal. 其中两个表:SummaryLocal_Bands和SummaryLocal_Averages与第三个表中的pk之间存在fk关系:SummaryLocal。 The tables in Sql Server have the same structure, columns, relationships, etc as the tables in this DataSet. Sql Server中的表具有与此DataSet中的表相同的结构,列,关系等。 Lets say I add rows to the DataTables in the DataSet so that they contain data. 可以说我将行添加到数据集中的数据表中,以便它们包含数据。 I then want to Insert their rows into the sql server tables (which contain the same structure as the datatables in the dataset as noted above). 然后,我想将它们的行插入sql服务器表(它们包含与如上所述的数据集中的数据表相同的结构)。 How hard is this to accomplish and how do I accomplish it? 这有多难完成,我该如何完成? Or is it smarter to accomplish this another way? 还是以另一种方式实现这一目标更明智?

Is seems like you want to persist the changes on your DataTables to it's underlying tables in the database..can't you just make a connection to database and make an insert statement?... 似乎您想将对DataTables的更改持久保存到数据库中的基础表中。.您是否不能仅连接数据库并执行插入语句?

Try creating a method that have the following commands below: (Note: it's just a skeleton of the commands that you need to do, fill them up according to your settings) 尝试创建一种下面具有以下命令的方法:(注意:这只是您需要执行的命令的框架,请根据您的设置将其填满)

string connectionString = "your_connection_string";  
SqlConnection con = new SqlConnection(connectionString);  

try  
{  
    con.Open();  
    string query = "insert statement";  

    using (SqlCommand cmd = new SqlCommand(query, con))  
    {  
        cmd.Parameters.AddWithValue("@some_parameter", "value_of_some_parameter");  
        cmd.ExecuteNonQuery();  
    }   
}  
catch (Exception)  
{  
throw;  
}  

Or, if your datatables are somehow not connected to a database, you can still use the above method by looping through the contents of your datatable. 或者,如果您的数据表未以某种方式未连接到数据库,则仍然可以通过遍历数据表的内容来使用上述方法。

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

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