当前位置:首页 > 行业动态 > 正文

c#批量导入sql数据库语句

摘要:本文介绍了C#中批量导入SQL数据库的方法,包括使用SqlBulk Copy类和DataTable、执行SQL命令插入多条记录等技术,以提高数据导入效率。

在C#中,批量导入SQL数据库语句可以通过多种方式实现,以下是几种常见的方法:

一、使用SqlCommand和循环

1、示例代码

假设有一个包含多条数据的列表,需要将这些数据插入到SQL Server的Students表中。

建立与数据库的连接。

遍历数据列表,为每条数据创建一个SqlCommand对象并执行插入语句。

“`csharp

using System;

using System.Data.SqlClient;

using System.Collections.Generic;

namespace BatchInsertExample

{

class Program

{

static void Main(string[] args)

{

string connectionString = "your_connection_string_here";

using (SqlConnection connection = new SqlConnection(connectionString))

{

List<Student> students = new List<Student>

{

new Student { Id = 1, Name = "Alice", Age = 20 },

new Student { Id = 2, Name = "Bob", Age = 22 },

//…添加更多学生数据

};

foreach (var student in students)

{

string sql = "INSERT INTO Students (Id, Name, Age) VALUES (@Id, @Name, @Age)";

using (SqlCommand command = new SqlCommand(sql, connection))

{

command.Parameters.AddWithValue("@Id", student.Id);

command.Parameters.AddWithValue("@Name", student.Name);

command.Parameters.AddWithValue("@Age", student.Age);

connection.Open();

command.ExecuteNonQuery();

connection.Close();

}

}

}

}

}

public class Student

{

public int Id { get; set; }

public string Name { get; set; }

public int Age { get; set; }

}

}

优缺点优点:代码相对简单,易于理解和实现,适用于数据量较小的情况。缺点:对于大量数据,性能较低,因为每次插入都需要单独建立数据库连接、创建命令对象和执行操作,会增加网络开销和数据库负担。
二、使用SqlTransaction和批量插入
1、示例代码 同样以向Students表插入多条学生数据为例。
   先建立数据库连接和事务。
   构建一个包含所有插入语句的字符串,然后一次性执行。
   ```csharp
     using System;
     using System.Data.SqlClient;
     using System.Text;
     namespace BatchInsertWithTransactionExample
     {
         class Program
         {
             static void Main(string[] args)
             {
                 string connectionString = "your_connection_string_here";
                 using (SqlConnection connection = new SqlConnection(connectionString))
                 {
                     connection.Open();
                     SqlTransaction transaction = connection.BeginTransaction();
                     try
                     {
                         StringBuilder sb = new StringBuilder();
                         sb.Append("INSERT INTO Students (Id, Name, Age) VALUES ");
                         for (int i = 0; i < 100; i++) // 假设有100条数据
                         {
                             sb.AppendFormat("(@Id{0}, @Name{0}, @Age{0})", i);
                             if (i < 99)
                             {
                                 sb.Append(", ");
                             }
                         }
                         string sql = sb.ToString();
                         using (SqlCommand command = new SqlCommand(sql, connection, transaction))
                         {
                             for (int i = 0; i < 100; i++)
                             {
                                 command.Parameters.AddWithValue("@Id" + i, i + 1);
                                 command.Parameters.AddWithValue("@Name" + i, "Student" + (i + 1));
                                 command.Parameters.AddWithValue("@Age" + i, 20 + i);
                             }
                             command.ExecuteNonQuery();
                             transaction.Commit();
                         }
                     }
                     catch (Exception ex)
                     {
                         transaction.Rollback();
                         Console.WriteLine("Error: " + ex.Message);
                     }
                 }
             }
         }
     }

优缺点

优点:通过事务可以保证数据的一致性和完整性,批量插入减少了网络开销和数据库的多次处理,提高了性能。

缺点:代码相对复杂一些,尤其是在构建动态SQL语句和添加参数时需要仔细处理,容易出现错误,如果数据量非常大,构建的SQL语句可能会很长,导致性能问题。

三、使用Table-Valued Parameters(仅适用于SQL Server 2008及更高版本)

1、示例代码

定义一个用户自定义的数据类型来表示要插入的数据结构。

在C#中创建该类型的实例并填充数据。

使用SqlCommand将该数据类型作为参数传递给存储过程或直接插入语句。

“`csharp

using System;

using System.Data.SqlClient;

using System.Data;

namespace TableValuedParametersExample

{

class Program

{

static void Main(string[] args)

{

string connectionString = "your_connection_string_here";

using (SqlConnection connection = new SqlConnection(connectionString))

{

DataTable dataTable = new DataTable();

dataTable.Columns.Add("Id", typeof(int));

dataTable.Columns.Add("Name", typeof(string));

dataTable.Columns.Add("Age", typeof(int));

for (int i = 0; i < 100; i++)

{

dataTable.Rows.Add(i + 1, "Student" + (i + 1), 20 + i);

}

string sql = "INSERT INTO Students (Id, Name, Age) SELECT Id, Name, Age FROM @StudentTable";

using (SqlCommand command = new SqlCommand(sql, connection))

{

command.Parameters.AddWithValue("@StudentTable", dataTable);

connection.Open();

command.ExecuteNonQuery();

connection.Close();

}

}

}

}

}

优缺点优点:可以一次性插入大量数据,性能较好,代码相对简洁,利用了数据库的批处理能力,减少了网络传输的次数。缺点:需要对数据库进行额外的配置和权限设置,以确保可以使用Table-Valued Parameters功能,并且不是所有的数据库都支持这种特性。
四、使用第三方库(如Dapper)
1、示例代码 Dapper是一个轻量级的ORM框架,可以方便地进行数据库操作,以下示例展示了如何使用Dapper批量插入数据。
   安装Dapper库:通过NuGet包管理器安装Dapper。
   ```csharp
     using System;
     using System.Collections.Generic;
     using System.Data.SqlClient;
     using Dapper;
     namespace DapperBatchInsertExample
     {
         class Program
         {
             static void Main(string[] args)
             {
                 string connectionString = "your_connection_string_here";
                 using (SqlConnection connection = new SqlConnection(connectionString))
                 {
                     List<Student> students = new List<Student>
                     {
                         new Student { Id = 1, Name = "Alice", Age = 20 },
                         new Student { Id = 2, Name = "Bob", Age = 22 },
                         //...添加更多学生数据
                     };
                     string sql = "INSERT INTO Students (Id, Name, Age) VALUES (@Id, @Name, @Age)";
                     connection.Open();
                     Dapper.Execute(connection, sql, students);
                     connection.Close();
                 }
             }
         }
         public class Student
         {
             public int Id { get; set; }
             public string Name { get; set; }
             public int Age { get; set; }
         }
     }

优缺点

优点:代码简洁,易于使用,性能较高,Dapper利用了数据库的批处理机制,减少了网络开销和数据库操作次数,它提供了灵活的参数映射方式,可以方便地处理复杂的数据结构和查询条件。

缺点:需要额外引入第三方库,对于一些简单的场景可能会显得有些“重量级”,不过在实际应用中,其优势通常更为明显。

在C#中进行批量导入SQL语句时,可以根据具体的应用场景和需求选择合适的方法,如果数据量较小且对性能要求不高,可以使用简单的循环和单个命令执行;如果需要保证数据的一致性和完整性,或者要导入大量数据以提高性能,可以考虑使用事务、Table-Valued Parameters或第三方库等方法。

0