programing tip

SqlDataAdapter 및 SqlDataReader

itbloger 2020. 7. 10. 08:06
반응형

SqlDataAdapter 및 SqlDataReader


DB에서 데이터를 가져 오기 위해 SqlDataAdapter와 SqlDataReader를 사용하는 것의 차이점은 무엇입니까?

나는 그들의 장단점뿐만 아니라 속도와 메모리 성능을 구체적으로 살펴보고 있습니다.

감사


SqlDataReader :

  • 끝날 때까지 연결을 유지합니다 (닫는 것을 잊지 마십시오!).
  • 일반적으로 한 번만 반복 할 수 있습니다
  • 데이터베이스로 다시 업데이트하는 데 유용하지 않습니다

반면에, 그것은 :

  • 전체 결과 세트가 아닌 한 번에 하나의 레코드 만 메모리에 있습니다 (대용량 일 수 있음)
  • 한 번의 반복으로 얻을 수있는 속도만큼 빠릅니다.
  • 결과 처리를 더 빨리 시작할 수 있습니다 (첫 번째 레코드를 사용할 수있는 경우)

SqlDataAdapter / DataSet

  • 데이터로드가 완료되면 바로 연결을 닫을 수 있으며 자동으로 닫을 수도 있습니다
  • 모든 결과는 메모리에서 사용할 수 있습니다
  • 필요한만큼 반복하거나 인덱스별로 특정 레코드를 조회 할 수 있습니다
  • 데이터베이스로 다시 업데이트하기위한 몇 가지 기본 기능이 있습니다.

비용 :

  • 훨씬 높은 메모리 사용
  • 데이터를 사용하기 전에 모든 데이터가로드 될 때까지 기다립니다

따라서 실제로는 수행중인 작업에 따라 다르지만 데이터 세트에서만 지원되는 항목이 필요할 때까지 DataReader를 선호하는 경향이 있습니다. SqlDataReader는 읽기 전용 그리드에 바인딩하는 일반적인 데이터 액세스 사례에 적합합니다.

자세한 내용 은 공식 Microsoft 설명서를 참조하십시오 .


그것에 대한 대답은 매우 광범위 할 수 있습니다.

기본적으로, 사용 결정에 영향을 미치는 주요 차이점은 SQLDataReader를 사용하면 데이터베이스에서 데이터를 "스트리밍"한다는 것입니다. SQLDataAdapter를 사용하면 데이터베이스에서 CRUD 조작을 수행 할뿐만 아니라 추가로 조회 할 수있는 오브젝트로 데이터를 추출합니다.

분명히 데이터 스트림을 사용하면 SQLDataReader가 훨씬 빠르지 만 한 번에 하나의 레코드 만 처리 할 수 ​​있습니다. SQLDataAdapter를 사용하면 데이터베이스에서 쿼리와 일치하는 행을 완전히 수집하여 코드를 처리 / 통과 할 수 있습니다.

경고 : SQLDataReader, ALWAYS, ALWAYS, ALWAYS를 사용하는 경우 SQLDataReader를 사용하여 연결을 계속 유지하므로 연결을 닫는 데 적합한 코드를 작성해야합니다. 이를 수행하지 않거나 결과 처리 오류가 발생하는 경우 연결을 닫는 올바른 오류 처리 는 연결 누수로 인해 응용 프로그램을 중단 시킵니다.

내 VB를 사면하지만 SqlDataReader를 사용할 때 필요한 최소 코드 양입니다.

Using cn As New SqlConnection("..."), _
      cmd As New SqlCommand("...", cn)

    cn.Open()
    Using rdr As SqlDataReader = cmd.ExecuteReader()
        While rdr.Read()
            ''# ...
        End While
    End Using
End Using     

동등한 C # :

using (var cn = new SqlConnection("..."))
using (var cmd = new SqlCommand("..."))
{
    cn.Open();
    using(var rdr = cmd.ExecuteReader())
    {
        while(rdr.Read())
        {
            //...
        }
    }
}

SqlDataAdapter는 일반적으로 DataSet 또는 DataTable을 채우는 데 사용되므로 연결이 종료 된 후 (연결이 끊긴 액세스) 데이터에 액세스 할 수 있습니다.

SqlDataReader는 일반적으로 DataSet / DataTable을 채우는 것보다 빠른 경향이있는 빨리 감기 전용 및 연결된 커서입니다.

Furthermore, with a SqlDataReader, you deal with your data one record at a time, and don't hold any data in memory. Obviously with a DataTable or DataSet, you do have a memory allocation overhead.

If you don't need to keep your data in memory, so for rendering stuff only, go for the SqlDataReader. If you want to deal with your data in a disconnected fashion choose the DataAdapter to fill either a DataSet or DataTable.


Use an SqlDataAdapter when wanting to populate an in-memory DataSet/DataTable from the database. You then have the flexibility to close/dispose off the connection, pass the datatable/set around in memory. You could then manipulate the data and persist it back into the DB using the data adapter, in conjunction with InsertCommand/UpdateCommand.

Use an SqlDataReader when wanting fast, low-memory footprint data access without the need for flexibility for e.g. passing the data around your business logic. This is more optimal for quick, low-memory usage retrieval of large data volumes as it doesn't load all the data into memory all in one go - with the SqlDataAdapter approach, the DataSet/DataTable would be filled with all the data so if there's a lot of rows & columns, that will require a lot of memory to hold.


The Fill function uses a DataReader internally. If your consideration is "Which one is more efficient?", then using a DataReader in a tight loop that populates a collection record-by-record, is likely to be the same load on the system as using DataAdapter.Fill.

(System.Data.dll, System.Data.Common.DbDataAdapter, FillInternal.)

참고URL : https://stackoverflow.com/questions/1676753/sqldataadapter-vs-sqldatareader

반응형