forked from dotnet/efcore
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
61 lines (50 loc) · 1.86 KB
/
Copy pathProgram.cs
File metadata and controls
61 lines (50 loc) · 1.86 KB
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
using System;
using System.Diagnostics;
using Microsoft.Data.Sqlite;
namespace BulkInsertSample
{
class Program
{
static void Main()
{
var connection = new SqliteConnection("Data Source=:memory:");
connection.Open();
var createCommand = connection.CreateCommand();
createCommand.CommandText =
@"
CREATE TABLE data (
value INTEGER
)
";
createCommand.ExecuteNonQuery();
// There is no special API for inserting data in bulk. For the best performance,
// follow this pattern.
Console.WriteLine("Inserting 150,000 rows...");
var stopwatch = Stopwatch.StartNew();
// Always use a transaction
using (var transaction = connection.BeginTransaction())
{
var insertCommand = connection.CreateCommand();
insertCommand.CommandText =
@"
INSERT INTO data
VALUES ($value)
";
// Re-use the same parameterized SqliteCommand
var valueParameter = insertCommand.CreateParameter();
valueParameter.ParameterName = "$value";
insertCommand.Parameters.Add(valueParameter);
// No need to call Prepare() since it's done lazily during the first execution.
//insertCommand.Prepare();
var random = new Random();
for (int i = 0; i < 150_000; i++)
{
valueParameter.Value = random.Next();
insertCommand.ExecuteNonQuery();
}
transaction.Commit();
}
Console.WriteLine($"Done. (took {stopwatch.ElapsedMilliseconds} ms)");
}
}
}