-
Notifications
You must be signed in to change notification settings - Fork 0
/
GenerateSqlSingularInserter.cs
77 lines (62 loc) · 2.78 KB
/
GenerateSqlSingularInserter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BulkInsertInvestigation
{
public class GenerateSqlSingularInserter
{
private string connectionString;
private int batchSize;
public GenerateSqlSingularInserter (string connectionString, int batchSize)
{
this.connectionString = connectionString;
this.batchSize = batchSize;
}
public void Insert(IEnumerable<Customer> dataRecords)
{
int inserted = 0;
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
var transaction = connection.BeginTransaction();
var command = connection.CreateCommand();
command.CommandText =
@"INSERT INTO Customers(Email, Name, [Address], IsActive, Latitude, Longitude)
VALUES (@Email, @Name, @Address, @IsActive, @Latitude, @Longitude)";
command.CommandType = CommandType.Text;
command.Transaction = transaction;
var emailParameter = new SqlParameter {ParameterName = "@Email"};
command.Parameters.Add(emailParameter);
var nameParameter = new SqlParameter {ParameterName = "@Name"};
command.Parameters.Add(nameParameter);
var addressParameter = new SqlParameter {ParameterName = "@Address"};
command.Parameters.Add(addressParameter);
var isActiveParameter = new SqlParameter {ParameterName = "@IsActive"};
command.Parameters.Add(isActiveParameter);
var latitudeParameter = new SqlParameter {ParameterName = "@Latitude"};
command.Parameters.Add(latitudeParameter);
var longitudeParameter = new SqlParameter {ParameterName = "@Longitude"};
command.Parameters.Add(longitudeParameter);
foreach (Customer customer in dataRecords)
{
emailParameter.Value = customer.Email;
nameParameter.Value = customer.Name;
addressParameter.Value = customer.Address;
isActiveParameter.Value = customer.IsActive;
latitudeParameter.Value = customer.Latitude;
longitudeParameter.Value = customer.Longitude;
command.ExecuteNonQuery();
if (++inserted%batchSize == 0)
{
Console.WriteLine("Inserted {0} customers", inserted);
}
}
transaction.Commit();
}
}
}
}