asp의 getrows와 getstring 사용법

10847 단어
GetRows 메서드
Recordset 객체의 여러 레코드를 배열에 복사합니다.
구문
array = recordset.GetRows( Rows, Start, Fields )
반환값
2D 배열을 반환합니다.
매개 변수
Rows 선택 사항, 로깅할 레코드 수를 지정하는 긴 정수 표현식입니다.기본값은 adGetRowsRest(-1)입니다.
GetRows 작업 시작 부분에 기록된 책갈피를 계산하는 문자열 또는 긴 정렬 옵션다음 BookmarkEnum 값도 사용할 수 있습니다.
상수는 AdBookmarkCurrent가 현재 레코드에서 시작됨을 나타냅니다.AdBookmarkFirst는 첫 번째 레코드부터 시작합니다.AdBookmarkLast는 마지막 레코드부터 시작합니다.
Fields는 단일 필드 이름, 순서 위치, 필드 이름 배열 또는 순서 위치 번호를 나타내는 선택 사항입니다.ADO는 이 필드의 데이터만 반환합니다.
설명
GetRows 방법을 사용하여 레코드를 Recordset에서 2D 배열로 복사합니다.첫 번째는 필드를 표시하고, 두 번째는 기록 번호를 표시한다.GetRows 메서드가 데이터를 반환하면 배열 변수가 자동으로 올바른 크기로 조정됩니다.
Rows 매개 변수의 값을 지정하지 않으면 GetRows 메서드는 Recordset 객체의 모든 레코드를 자동으로 읽어들입니다.요청한 레코드가 사용 가능한 레코드보다 많은 경우 GetRows는 사용 가능한 레코드 수만 반환합니다.
Recordset 객체가 책갈피를 지원할 경우 해당 레코드의 Bookmark 속성 값을 전송하여 GetRows 메서드가 어떤 레코드로부터 데이터를 검색할지 지정할 수 있습니다.
GetRows 호출이 되돌아오는 필드를 제한하려면 Fields 매개 변수에서 하나의 필드 이름/번호 또는 필드 이름/번호 그룹을 전송할 수 있습니다.
GetRows를 호출한 후 읽지 않은 다음 기록이 현재 기록이 되거나 더 많은 기록이 없으면 EOF 속성이 True로 설정됩니다.
 
GetString 메서드
데이터베이스 표시 테이블을 질의할 때 Do While()...Loop이나 For...많은 양의 데이터를 조회할 때 반드시 느릴 수 있도록 Next 순환을 통해 표를 표시합니다.이 때 우리는 기록집 대상이 제공하는 GetString () 방법 (ADO는 2.0으로 업그레이드해야 함) 을 사용할 수 있다.
구문
Str=objRecordset.GetString(format,n,coldel,rowdel,nullexpr)
매개 변수 설명: objRecordset: 열린 레코드세트 객체,format: 선택할 수 있습니다. 일반적으로 기본값(기본값 2)n: 선택할 수 있습니다. 기록의 수량을 표시할 수 있습니다. 기본값은 모두coldel: 선택할 수 있습니다. 열 구분자rowdel: 선택할 수 있습니다. 줄 구분자nullexpr: 선택할 수 있습니다. 이 매개 변수는 빈 필드를 채우는 데 사용됩니다!
GetString 방법이 있으면, 우리는 단지 하나의 Response를 사용할 수 있다.Write는 모든 출력을 보여줍니다. Recordset이 EOF의 DO인지 아닌지를 판단할 수 있는 것 같습니다.LOOP 순환은 이 방법으로 문자열을 자동으로 순환하여 출력할 수 있다.while이나 for 순환을 하지 않아도 된다.RS 대상을 구축하고 해당하는 조작을 실행하면 그것이 한 개의 기록이든 여러 개의 기록이든 심지어 빈 기록이든 getstring은 그대로 작업한다.Recordset 결과에서 HTML 표를 만들려면 GetString의 5개 매개 변수 중 3개: coldel (레코드세트의 열을 구분하는 HTML 코드),rowdel (레코드세트의 줄을 구분하는 HTML 코드),nullexpr (현재 레코드가 비어 있을 때 생성해야 하는 HTML 코드) 에만 관심을 가져야 합니다.
<TABLE Border=1>
<TR><TD>
<% = Response.Write rs.GetString( , , "</TD><TD>", "</TD></TR><TR>", ) %>
</TABLE> 

이렇게 쓴 HTML 결과는 다음과 같습니다.
<TABLE Border=1>
<TR>
<TD>row1, field1 value</TD>
<TD>row1, field2 value</TD>
</TR>
<TR>
<TD>row2, field1 value</TD>
<TD>row2, field2 value</TD>
</TR>
</TABLE>

여기에 BUG가 있어요. 다음 메뉴를 생성해 보세요.
<% 
Set RS = conn.Execute("SELECT theValue,theText FROM selectOptionsTable ORDER BY theText") 

optSuffix = "</OPTION>" & vbNewLine 
valPrefix = "<OPTION Value='" 
valSuffix = "'>" 
opts = RS.GetString( , , valSuffix, optSuffix & valPrefix, "--error--" ) 
' Next line is the key to it! 
opts = Left( opts, Len(opts)-Len(valPrefix) ) 

Response.Write "<SELECT ...>" & vbNewLine 
Response.Write valPrefix & opts 
Response.Write "</SELECT>" 
%> 


 
정확한 양식을 만들고 싶다면 그 BUG를 해결하고 이렇게 하면 된다.
<% 
Set RS = conn.Execute("SELECT * FROM table") 

tdSuffix = "</TD>" & vbNewLine & "<TD>
trPrefix = "<TR>" & vbNewLine & "<TD>" 
trSuffix = "</TD>" & vbNewLine & "</TR>" & vbNewLine & "<TR>" & vbNewLine
opts = RS.GetString( , , tdSuffix, trSuffix & trPrefix, "--error--" ) 
' Next line is the key to it! 
opts = Left( opts, Len(opts)-Len(trPrefix) ) 

Response.Write "<TABLE Border=1 CellPadding=5>" & vbNewLine 
Response.Write trPrefix & opts 
Response.Write "</TABLE>" & vbNewLine
%> 


------------------------------------------------------------------완전히 다른 방법을 하나 더 소개합니다
<% 
SQL = "SELECT '<OPTION Value=''',value,'''>',text,'</OPTION>' FROM table ORDER BY text" 
Set RS = conn.Execute(SQL) 
Response.Write "<SELECT>" & vbNewLine & RS.GetString(,,"",vbNewLine) & "</SELECT>"
%> 

써보셨어요...
보이시나요?질의에서 결과를 직접 반환할 수 있습니다.한 걸음 더 나아가면 당신은 이렇게 할 수 있습니다
<% 
SQL = "SELECT '<OPTION Value=''' & value & '''>' & text & '</OPTION>' FROM table ORDER BY text" 
Set RS = conn.Execute(SQL) 
Response.Write "<SELECT>" & vbNewLine & RS.GetString(,,"",vbNewLine) & "</SELECT>"
%> 

다음은 Script Output:
711855
Wednesday
23
3/23/2005 1:33:37 AM
711856
Wednesday
23
3/23/2005 1:23:00 AM
711857
Wednesday
23
3/23/2005 1:26:34 AM
711858
Wednesday
23
3/23/2005 1:33:53 AM
711859
Wednesday
23
3/23/2005 1:30:36 AM
ASP 코드는 다음과 같습니다.
<%
' Selected constants from adovbs.inc:
Const adClipString = 2

' Declare our variables... always good practice!
Dim cnnGetString   ' ADO connection
Dim rstGetString   ' ADO recordset
Dim strDBPath      ' Path to our Access DB (*.mdb) file
Dim strDBData      ' String that we dump all the data into
Dim strDBDataTable ' String that we dump all the data into                   
                   ' only this time we build a table
' MapPath to our mdb file's physical path.
strDBPath = Server.MapPath("db_scratch.mdb")

' Create a Connection using OLE DB
Set cnnGetString = Server.CreateObject("ADODB.Connection")

' This line is for the Access sample database:
'cnnGetString.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strDBPath & ";"
' We're actually using SQL Server so we use this line instead.
' Comment this line out and uncomment the Access one above to
' play with the script on your own server.
cnnGetString.Open "Provider=SQLOLEDB;Data Source=10.2.1.214;" _
& "Initial Catalog=samples;User Id=samples;Password=password;" _
& "Connect Timeout=15;Network Library=dbmssocn;"

' Execute a simple query using the connection object.
' Store the resulting recordset in our variable.
Set rstGetString = cnnGetString.Execute("SELECT * FROM scratch")

' Now this is where it gets interesting... Normally we'd do
' a loop of some sort until we ran into the last record in
' in the recordset.  This time we're going to get all the data
' in one fell swoop and dump it into a string so we can
' disconnect from the DB as quickly as possible.
strDBData = rstGetString.GetString()

' Since I'm doing this twice for illustration... I reposition
' at the beginning of the RS before the second call.
rstGetString.MoveFirst

' This time I ask for everything back in HTML table format:
strDBDataTable = rstGetString.GetString(adClipString, -1, _
&"</td><td>", "</td></tr>" & vbCrLf & "<tr><td>", "&nbsp;")

' Because of my insatiable desire for neat HTML, I actually
' truncate the string next.  You see, GetString only has
' a parameter for what goes between rows and not a seperate
' one for what to place after the last row.  Because of the
' way HTML tables are built, this leaves us with an extra
' <tr><td> after the last record.  GetString places the
' whole delimiter at the end since it doesn't have anything
' else to place there and in many situations this works fine.
' With HTML it's a little bit weird.  Most developers simply
' close the row and move on, but I couldn't bring myself to'
 leave the extra row... especially since it would have a
' different number of cells then all the others.
' What can I say... these things tend to bother me.  ;)
strDBDataTable = Left(strDBDataTable, Len(strDBDataTable) - Len("<tr><td>"))

' Some notes about .GetString:
' The Method actually takes up to 5 optional arguments:
' 1. StringFormat    - The format in which to return the
'                      recordset text. adClipString is the only
'                      valid value.
' 2. NumRows         - The number of rows to return.  Defaults
'                      to  -1 indicating all rows.
' 3. ColumnDelimiter - The text to place in between the columns.
'                      Defaults to a tab character
' 4. RowDelimiter    - The text to place in between the rows
'                      Defaults to a carriage return
' 5. NullExpr        - Expression to use if a NULL value is
'                      returned.  Defaults to an empty string.
' Close our recordset and connection and dispose of the objects.
' Notice that I'm able to do this before we even worry about
' displaying any of the data!
rstGetString.Close
Set rstGetString = Nothing
cnnGetString.Close
Set cnnGetString = Nothing

' Display the table of the data.  I really don't need to do
' any formatting since the GetString call did most everything
' for us in terms of building the table text.
Response.Write "<table border=""1"">" & vbCrLf
Response.Write "<tr><td>"
Response.Write strDBDataTable
Response.Write "</table>" & vbCrLf
' FYI: Here's the output format you get if you cann GetString
' without any parameters:
Response.Write vbCrLf & "<p>Here's the unformatted version:</p>" & vbCrLf
Response.Write "<pre>" & vbCrLf
Response.Write strDBDataResponse.Write "</pre>" & vbCrLf

' That's all folks!
%>

텍스트 링크:http://blog.csdn.net/vince6799/article/details/5891965

좋은 웹페이지 즐겨찾기