개발자

C# winform에서 대용량 엑셀파일 저장

2023년 07월 12일조회 435

엑셀에서 4만줄 정도 되는 데이터를 읽어와 DB에 저장하는 작업을 진행하고 있습니다. 그런데 읽어 들이는 시간은 얼마 안걸리는데 db로 저장할때 시간이 몇십분이 걸리더라구요. 속도 개선하는 방법은 어떤게 있을까요??

이 질문이 도움이 되었나요?
'추천해요' 버튼을 누르면 좋은 질문이 더 많은 사람에게 노출될 수 있어요. '보충이 필요해요' 버튼을 누르면 질문자에게 질문 내용 보충을 요청하는 알림이 가요.

답변 1

커리어리 AI 봇님의 프로필 사진

C#에서 대용량 데이터를 DB에 저장하는 시간을 줄이는 방법에는 여러가지가 있습니다. 아래에 몇 가지 방법을 제시해 드리겠습니다: 1. 일괄 처리(Bulk Insert): 데이터베이스에 대량의 데이터를 저장할 때, 하나의 쿼리문으로 많은 양의 데이터를 한 번에 저장하는 것입니다. SQL Server에서는 `SqlBulkCopy` 클래스를 사용하면 일괄 처리를 할 수 있습니다. 2. 트랜잭션 사용: 한 번에 많은 데이터를 저장하려면 트랜잭션을 사용하면 효과적입니다. 모든 쿼리를 하나의 트랜잭션으로 묶어서 실행하면, 데이터베이스는 이를 하나의 단일 작업으로 취급하므로 성능이 향상됩니다. 3. 인덱스 최적화: 데이터베이스에 저장하는 데이터의 필드 중에서 검색에 자주 사용되는 필드에 대해 인덱스를 생성하면, 데이터 삽입 속도를 높일 수 있습니다. 이런 방법들을 적용해보시고, 아직도 속도 개선이 충분하지 않다면 데이터베이스 구조 자체를 점검해 보는 것도 필요합니다.

1#1
2using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connectionString))
3{
4    bulkCopy.DestinationTableName = "dbo.BulkCopyDemoMatchingColumns";
5
6    try
7    {
8        // Write from the source to the destination.
9        bulkCopy.WriteToServer(reader);
10    }
11    catch (Exception ex)
12    {
13        Console.WriteLine(ex.Message);
14    }
15    finally
16    {
17        // Close the SqlDataReader. The SqlBulkCopy
18        // object is automatically closed at the end
19        // of the using block.
20        reader.Close();
21    }
22}
23
24
25#2
26using (SqlConnection connection = new SqlConnection(connectionString))
27{
28    connection.Open();
29
30    SqlCommand command = connection.CreateCommand();
31    SqlTransaction transaction;
32
33    // Start a local transaction.
34    transaction = connection.BeginTransaction("SampleTransaction");
35
36    // Must assign both transaction object and connection 
37    // to Command object for a pending local transaction
38    command.Connection = connection;
39    command.Transaction = transaction;
40
41    try
42    {
43        command.CommandText = 
44            "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
45        command.ExecuteNonQuery();
46        command.CommandText = 
47            "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
48
49        command.ExecuteNonQuery();
50
51        // Attempt to commit the transaction.
52        transaction.Commit();
53        Console.WriteLine("Both records are written to database.");
54    }
55    catch (Exception ex)
56    {
57        Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
58        Console.WriteLine("  Message: {0}", ex.Message);
59
60        // Attempt to roll back the transaction. 
61        try
62        {
63            transaction.Rollback();
64        }
65        catch (Exception ex2)
66        {
67            // This catch block will handle any errors that may have occurred 
68            // on the server that would cause the rollback to fail, such as 
69            // a closed connection.
70            Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
71            Console.WriteLine("  Message: {0}", ex2.Message);
72        }
73    }
74}

커리어리 AI 봇의 답변을 평가해 주세요!

지금 가입하면 모든 질문의 답변을 볼 수 있어요!

현직자들의 명쾌한 답변을 얻을 수 있어요.

또는

이미 회원이신가요?

목록으로

지금 가입하면 모든 질문의 답변을 볼 수 있어요!