개발자
엑셀에서 4만줄 정도 되는 데이터를 읽어와 DB에 저장하는 작업을 진행하고 있습니다. 그런데 읽어 들이는 시간은 얼마 안걸리는데 db로 저장할때 시간이 몇십분이 걸리더라구요. 속도 개선하는 방법은 어떤게 있을까요??
답변 1
C#에서 대용량 데이터를 DB에 저장하는 시간을 줄이는 방법에는 여러가지가 있습니다. 아래에 몇 가지 방법을 제시해 드리겠습니다: 1. 일괄 처리(Bulk Insert): 데이터베이스에 대량의 데이터를 저장할 때, 하나의 쿼리문으로 많은 양의 데이터를 한 번에 저장하는 것입니다. SQL Server에서는 `SqlBulkCopy` 클래스를 사용하면 일괄 처리를 할 수 있습니다. 2. 트랜잭션 사용: 한 번에 많은 데이터를 저장하려면 트랜잭션을 사용하면 효과적입니다. 모든 쿼리를 하나의 트랜잭션으로 묶어서 실행하면, 데이터베이스는 이를 하나의 단일 작업으로 취급하므로 성능이 향상됩니다. 3. 인덱스 최적화: 데이터베이스에 저장하는 데이터의 필드 중에서 검색에 자주 사용되는 필드에 대해 인덱스를 생성하면, 데이터 삽입 속도를 높일 수 있습니다. 이런 방법들을 적용해보시고, 아직도 속도 개선이 충분하지 않다면 데이터베이스 구조 자체를 점검해 보는 것도 필요합니다.
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
#1 using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connectionString)) { bulkCopy.DestinationTableName = "dbo.BulkCopyDemoMatchingColumns"; try { // Write from the source to the destination. bulkCopy.WriteToServer(reader); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { // Close the SqlDataReader. The SqlBulkCopy // object is automatically closed at the end // of the using block. reader.Close(); } } #2 using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command = connection.CreateCommand(); SqlTransaction transaction; // Start a local transaction. transaction = connection.BeginTransaction("SampleTransaction"); // Must assign both transaction object and connection // to Command object for a pending local transaction command.Connection = connection; command.Transaction = transaction; try { command.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')"; command.ExecuteNonQuery(); command.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')"; command.ExecuteNonQuery(); // Attempt to commit the transaction. transaction.Commit(); Console.WriteLine("Both records are written to database."); } catch (Exception ex) { Console.WriteLine("Commit Exception Type: {0}", ex.GetType()); Console.WriteLine(" Message: {0}", ex.Message); // Attempt to roll back the transaction. try { transaction.Rollback(); } catch (Exception ex2) { // This catch block will handle any errors that may have occurred // on the server that would cause the rollback to fail, such as // a closed connection. Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType()); Console.WriteLine(" Message: {0}", ex2.Message); } } }
커리어리 AI 봇의 답변을 평가해 주세요!
지금 가입하면 모든 질문의 답변을 볼 수 있어요!
현직자들의 명쾌한 답변을 얻을 수 있어요.
이미 회원이신가요?
지금 가입하면 모든 질문의 답변을 볼 수 있어요!