C# DataTable數(shù)據(jù)插入有哪些策略

c#
小樊
81
2024-10-12 18:42:22

在C#中,使用DataTable數(shù)據(jù)插入有多種策略。以下是一些常用的方法:

  1. 使用DataAdapter和SqlCommandBuilder:
    • 創(chuàng)建一個(gè)SqlConnection對(duì)象連接到數(shù)據(jù)庫(kù)。
    • 創(chuàng)建一個(gè)SqlDataAdapter對(duì)象,用于填充DataTable。
    • 使用SqlCommandBuilder對(duì)象從DataTable生成SQL命令。
    • 使用SqlDataAdapter的Fill方法將數(shù)據(jù)插入到數(shù)據(jù)庫(kù)表中。
string connectionString = "your_connection_string";
string query = "SELECT * FROM your_table";

using (SqlConnection con = new SqlConnection(connectionString))
{
    con.Open();

    using (SqlDataAdapter da = new SqlDataAdapter(query, con))
    {
        DataTable dt = new DataTable();
        da.Fill(dt);

        using (SqlCommandBuilder cb = new SqlCommandBuilder(da))
        {
            foreach (DataRow row in dt.Rows)
            {
                cb.Update(row);
            }
        }
    }
}
  1. 使用SqlBulkCopy:
    • 創(chuàng)建一個(gè)SqlConnection對(duì)象連接到數(shù)據(jù)庫(kù)。
    • 創(chuàng)建一個(gè)SqlBulkCopy對(duì)象,用于將數(shù)據(jù)插入到數(shù)據(jù)庫(kù)表中。
    • 將DataTable的內(nèi)容復(fù)制到SqlBulkCopy對(duì)象中。
    • 使用SqlBulkCopy的WriteToServer方法將數(shù)據(jù)插入到數(shù)據(jù)庫(kù)表中。
string connectionString = "your_connection_string";
string tableName = "your_table";

using (SqlConnection con = new SqlConnection(connectionString))
{
    con.Open();

    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(tableName, con))
    {
        bulkCopy.ColumnMappings.Add("column1", "column1");
        bulkCopy.ColumnMappings.Add("column2", "column2");
        // 添加更多列映射

        DataTable dt = new DataTable();
        // 填充DataTable

        bulkCopy.WriteToServer(dt);
    }
}
  1. 使用Entity Framework:
    • 創(chuàng)建一個(gè)實(shí)體框架上下文對(duì)象。
    • 將DataTable轉(zhuǎn)換為實(shí)體框架可以識(shí)別的對(duì)象集合。
    • 使用上下文的SaveChanges方法將數(shù)據(jù)插入到數(shù)據(jù)庫(kù)表中。
using (var context = new YourDbContext())
{
    foreach (DataRow row in dt.Rows)
    {
        var entity = new YourEntity
        {
            Column1 = row["column1"].ToString(),
            Column2 = row["column2"].ToString()
            // 設(shè)置更多屬性
        };

        context.YourEntities.Add(entity);
    }

    context.SaveChanges();
}

這些策略各有優(yōu)缺點(diǎn),選擇哪種策略取決于你的具體需求和場(chǎng)景。例如,如果你需要處理大量數(shù)據(jù)并且對(duì)性能有較高要求,那么使用SqlBulkCopy可能是最佳選擇。如果你需要與數(shù)據(jù)庫(kù)進(jìn)行更復(fù)雜的交互,例如更新或刪除記錄,那么使用Entity Framework可能更方便。

0