본문 바로가기
컴퓨터이야기/ASP&.NET

ASP에서 데이터를 가지고 오는 가장 효과적인 방법, GetRows

by 변화지시자 2009. 8. 5.
반응형

아 직도 데이터베이스에서 데이터를 가지고 올 때 반복문 안에서 Movenext를 사용하는가? 그렇다면 이 글을 관심있게 살펴 보기 바란다. 대부분의 사람들이 데이터베이스에서 데이터를 가지고 올 때 다음과 같은 방식을 이용하여 데이터를 가지고 온다.

<%
' 데이터베이스 오픈
Do UNTIL rs.eof
    name=rs("name")
    address=rs("address")
    company=rs("company")
    rs.movenext
    '사용자게에 데이터를 보여주기 위한 처리...
LOOP
%>

 

만일 예를 들어, 3개의 컬럼에 700개의 레코드를 가지고 온다고 가정해 보자. 만일 그렇다면 아래 공식처럼 전체 3,500번의 데이터베이스 접근을 시도해야 한다.

+ 2,100 ..... 각각의 필드를 읽을 때 마다 데이터베이스 요청 (700 * 3)
+ 700    ..... 각각의 movenext 마다 1회씩 총 700회 요청
+ 700    ..... 각각의 eof 테스트마다 1회씩 총 700회 요청
=======
= 3,500

 

만일 가지고와야할 데이터가 많으면 많을 수록 더 많은 요청이 이루어질 것이고 그에 따른 성능 저하가 예상이 된다.

 

그렇다면 3,500번의 요청이 예상되는 위의 예를 단 한 번의 요청으로 같은 결과를 가지고 올 수 있을까? 있다. 바로 GetRows를 사용하는 것이다. 다음과 같은 방식으로 GetRows를 사용할 수 있다:

dim myArray
myArray = rs.GetRows

 

3개의 컬럼을 가진 700개의 레코드를 단 한 번에 배열로 저장시킬 수 있다. 이것은 데이터를 가지고 오기 위해 매번 데이터베이스와 통신을 하지 않아도 배열 메모리에 저장해 두고 그 데이터들을 사용할 수 있음을 의미한다. 심지어 데이터를 사용하기 전에 Recordset, Connection 객체 리소스를 반환해도 됨을 의미한다.

 

이제 실제 코드를 한 번 살펴보도록 하자.

<html><head>
<TITLE>GetRows를 사용한 예제</TITLE>
</head>
<body bgcolor="#FFFFFF">
<%
' 자신의 환경에 맞는 데이터베이스 정보 입력
myDSN="Provider=SQLOLEDB; Data Source=(local); Initial Catalog=pubs; User ID=sa; Password=1111"
' 자신에게 맞는 SQL문 설정
mySQL="select * from authors"
showblank="&nbsp;"
shownull="-null-"

set conntemp=server.createobject("adodb.connection")
conntemp.open myDSN
set rstemp=conntemp.execute(mySQL)
If  rstemp.eof then
   response.write "해당 데이터가 존재하지 않습니다!<br>"
   response.write "조회하신 SQL 문 : " & mySQL
   Call CloseAll
   response.end
end if

response.write "<table border='1' cellspacing='0' cellpadding='5' bordercolordark='white' bordercolorlight='black'><tr>" & vbcrlf
'테이블 제목 표시
for each whatever in rstemp.fields
   response.write "<td><b>" & whatever.name & "</B></TD>" & vbcrlf
next
response.write "</tr>" & vbcrlf

' 모든 레코드를 배열로 저장
alldata=rstemp.getrows
Call CloseAll

numcols=ubound(alldata,1)
numrows=ubound(alldata,2)
FOR rowcounter= 0 TO numrows
   response.write "<tr>" & vbcrlf
   FOR colcounter=0 to numcols
      thisfield=alldata(colcounter,rowcounter)
      if isnull(thisfield) then
         thisfield=shownull
      end if
      if trim(thisfield)="" then
         thisfield=showblank
      end if
      response.write "<td valign=top>"
      response.write thisfield
      response.write "</td>" & vbcrlf
   NEXT
   response.write "</tr>" & vbcrlf
NEXT
response.write "</table>"
%>

</body></html>
<%
SUB CloseAll
   rstemp.close
   set rstemp=nothing
   conntemp.close
   set conntemp=nothing
END SUB
%>

 

자료출처 : http://korea.internet.com/