DB연결해서 테이블의 데이터 값과 개수를 출력하는 예제문이다.

 

 

[결과 화면] [DB 쿼리문 출력 결과]

 

코드

<%
-- DB 연결
Set oraConn = Server.CreateObject("ADODB.Connection")
oraConn.Open("dsn=[dsn];uid=[id];pwd=[password]")

Set oraRec = Server.CreateObject("ADODB.Recordset")
			
    sql = "select * from emp" 
	oraRec.Open sql, oraConn
%>

<html>
    <head>
    <title>예제 - 여러 개 데이터 출력하기</title>
    </head>
    <body>
    <%If OraRec.EOF Then %>
        <p>데이터가 없습니다.</p>
        <p>감사합니다.</p>
    <%Else %>
        <h2>쿼리 결과로 가져온 데이터입니다.</h2><hr />
        <%Dim count %>
        <%Do While Not OraRec.EOF %>
        <p>
        번호는 <b><%=OraRec.Fields("EMPNO")%> </b>,
        이름은 <b><%=OraRec.Fields("ENAME")%> </b>,
        직업는 <b><%=OraRec.Fields("JOB")%> </b>,
        부서이름은 <b><%=OraRec.Fields("DEPTNO")%> </b> 입니다.
        </p>

        <%OraRec.MoveNext%>
        <%count = count+1 %>
        <%Loop %>
    <b><%=count%></b>개 찾았습니다.
    <%End If %>
    </body>					
</html>

 

코드 리뷰

<%If OraRec.EOF Then %>
  <p>데이터가 없습니다.</p>
  <p>감사합니다.</p>
<%Else %>
  <h2>쿼리 결과로 가져온 데이터입니다.</h2>
<%End If %>
  • 데이터가 없는 경우 OraRec.EOF : true > "데이터가 없습니다." 출력 
  • 데이터가 있는 경우 OraRec.EOF : false > "쿼리 결과로 가져온 데이터입니다." 출력

 

 <%Dim count %>
 <%Do While Not OraRec.EOF %>
 <p>
 번호는 <b><%=OraRec.Fields("EMPNO")%> </b>,
 이름은 <b><%=OraRec.Fields("ENAME")%> </b>,
 직업는 <b><%=OraRec.Fields("JOB")%> </b>,
 부서이름은 <b><%=OraRec.Fields("DEPTNO")%> </b> 입니다.
 </p>
<%OraRec.MoveNext%>
<%count = count+1 %>
<%Loop %>
<b><%=count%></b>개 찾았습니다.
  • Dim count 변수 선언
  • While Not OraRec.EOF(데이터가 있으니까 false)  > 앞에 Not을 붙여줘서 true 됨 > 데이터가 있는 동안 실행
  • OraRec.Fields("필드명")으로 필드 출력
  • OraRec.MoveNext로 다음 레코드로 넘어감
  • count에 1씩 더해주면서 개수 저장

 

[출처] sugame.tistory.com/221

 

문자열 관련 함수
UCASE, LCASE 문자열의 내용을 대문자, 소문자로 변환
LEN 문자열의 길이를 반환
LEFT, RIGHT, MID 문자열의 좌, 우, 중간에서 지정한 만큼의 문자열을 뽑아냄
INSTR, INSTRREV 해당되는 문자열의 좌측, 우측 위치를 반환
LTRIM, RTRIM, TRIM 문자열의 좌측, 우측, 전체의 공백을 제거
REPLACE 문자열의 내용 중 일부를 다른 문자열로 변경
SPLIT 문자열에서 특정 문자열을 기준으로 나누어 배열로 저장
STRREVERSE 문자열의 순서가 거꾸로 된 문자열을 반환


1. UCASE, LCASE 사용

<h1>1. Uppercase or lowercase a string </h1>
<%
name = "Bill Gates"
response.write(ucase(name))
response.write("<br>")
response.write(lcase(name))
%>

 

2. TRIM, LTRIM, RTRIM 사용

<h1>2. Trim a string</h1>
<%
name = " W3Schools "
response.write("visit" & name & "now<br>")
response.write("visit" & trim(name) & "now<br>")
response.write("visit" & ltrim(name) & "now<br>")
response.write("visit" & rtrim(name) & "now")
%>

 

3. STRREVERSE 사용

<h1>3. How to reverse a string?</h1>
<%
sometext = "Hello Everyone!"
response.write(strReverse(sometext))
%>

 

4. ROUND 사용

<h1>4. How to round a number?</h1>
<%
i = 48.66776677
j = 48.33333
response.write(Round(i))
response.write("<br>")
response.write(Round(j))
%>

 

5. Randomize / Rnd : 랜덤 / 난수 생성

* Randomize란?

ASP에서 랜덤한 숫자를발생시키는 것은 Rnd 함수인데, Rnd 함수를 사용하기 전에 Randomize를 사용하여야 난수 발생기가 초기화되어 Rnd함수를 사용하였을 때 새로운 난수가 발생한다.

* Rnd란?

0부터 1사이의 랜덤한 숫자를 발생시키는 함수

<h1>5. A random number</h1>
<%
randomize()
response.write(rnd())
%>
<br>
<%
Randomize()
randomNumber=Int(100*Rnd())
response.write("A random number : <b>" & randomNumber & "</b>")
%>

 

6. LEFT, RIGHT, MID, REPLACE 사용

<h2>6. Return a specified number of characters from left/right of a string</h2>
<%
sometext="Welcome to this Web"
response.write(Left(sometext, 5))
response.write("<br>")
response.write(Right(sometext, 5))
response.write("<br>")
response.write(Mid(sometext, 9, 2))
response.write("<br>")
response.write(Replace(sometext, "Web", "Page"))
%> 

 

7. Sub Procedure 사용

<h1>7. Sub Procedure</h1>
<%
Sub mysub()
	response.write("I was written by a sub procedure")
End Sub

response.write("I was written by the script<br>")
Call mysub()
%>

 

8. Function Procedure 사용

<h1>8. Function Procedure</h1>
<%
Function myfunction()
myfunction=Date()
End Function

response.write("Today's date : ")
response.write(myfunction())
%>

 

 

[출처] www.w3schools.com/asp/asp_examples.asp

1. Date and time

<html>
<body>

Today's date is: <%response.write(date())%>.
<br>
The server's local time is: <%response.write(time())%>.

</body>
</html>

 

2. Get the name of a day

<html>
<body>

<p>
VBScripts' function <b>WeekdayName</b> is used to get a weekday:
</p>
<%
response.Write(WeekDayName(1))
response.Write("<br>")
response.Write(WeekDayName(2))
%>

<p>Abbreviated name of a weekday:</p>
<%
response.Write(WeekDayName(1,true))
response.Write("<br>")
response.Write(WeekDayName(2,true))
%>

<p>Current weekday:</p>
<%
response.Write(WeekdayName(weekday(date)))
response.Write("<br>")
response.Write(WeekdayName(weekday(date), true))
%>

</body>
</html>

 

3. Get the name of a month 

<html>
<body>

<p>VBScripts' function <b>MonthName</b> is used to get a month:</p>
<%
response.Write(MonthName(1))
response.Write("<br>")
response.Write(MonthName(2))
%>

<p>Abbreviated name of a month:</p>
<%
response.Write(MonthName(1,true))
response.Write("<br>")
response.Write(MonthName(2,true))
%>

<p>Current month:</p>
<%
response.Write(MonthName(month(date)))
response.Write("<br>")
response.Write(MonthName(month(date), true))
%>

</body>
</html>

 

4. Get todays' day and month

<html>
<body>

Today it is
<%response.write(WeekdayName(weekday(date)))%>,
<br>
and the month is
<%response.write(MonthName(month(date)))%>

</body>
</html>

 

5. Countdown to year 3000

<html>
<body>

<p>Countdown to year 3000:</p>

<p>
<%millennium=cdate("1/1/3000 00:00:00")%>

It is
<%response.write(DateDiff("yyyy", Now(), millennium))%>
years to year 3000!
<br>
It is
<%response.write(DateDiff("m", Now(), millennium))%>
months to year 3000!
<br>
It is
<%response.write(DateDiff("ww", Now(), millennium))%>
weeks to year 3000!
<br>
It is
<%response.write(DateDiff("d", Now(), millennium))%>
days to year 3000!
<br>
It is
<%response.write(DateDiff("h", Now(), millennium))%>
hours to year 3000!
<br>
It is
<%response.write(DateDiff("n", Now(), millennium))%>
minutes to year 3000!
<br>
It is
<%response.write(DateDiff("s", Now(), millennium))%>
seconds to year 3000!
</p>

</body>
</html>

 

6. Calculate the day which is n days from today

<html>
<body>

<%
response.write(DateAdd("d",30,Date()))
%>

<p>
This example uses <b>DateAdd</b> to calculate a date 30 days from today.
</p>
<p>
Syntax for DateAdd: DateAdd(interval,number,date).
</p>

<%
response.write(DateAdd("d",10,Date()))
%>

<p>
This example uses <b>DateAdd</b> to calculate a date 10 days from today.
</p>
<p>
Syntax for DateAdd: DateAdd(interval,number,date).
</p>

</body>
</html>

 

7. Format date and time

<html>
<body>

<%
response.write(FormatDateTime(date(),vbgeneraldate))
response.write("<br>")
response.write(FormatDateTime(date(),vblongdate))
response.write("<br>")
response.write(FormatDateTime(date(),vbshortdate))
response.write("<br>")
response.write(FormatDateTime(now(),vblongtime))
response.write("<br>")
response.write(FormatDateTime(now(),vbshorttime))
%>

<p>
Syntax for FormatDateTime: FormatDateTime(date,namedformat).
</p>

</body>
</html>

 

8. Is this a date?

<html>
<body>

<%
somedate="10/40/11"
response.write(IsDate(somedate))
response.write("<br>")
somedate="18/30/99"
response.write(IsDate(somedate))
response.write("<br>")
somedate="10/30/99"
response.write(IsDate(somedate))
%>

</body>
</html>

 

[출처] www.w3schools.com/asp/asp_examples.asp

ASP에서 레코드셋을 이용하여 레코드를 이동하는 방법

 

DB 오픈할 때 커서 타입을 지정해 줘야 한다.

 ex) Rs.Open SQL, DB, 1 (MoveNext와 MoveFirst만 사용시에는 1없어도 됨)

다음 레코드로 이동 rs.MoveNext
이전 레코드로 이동 rs.MovePrevious
처음 레코드로 이동 rs.MoveFirst
마지막 레코드로 이돌 rs.MoveLast
총 레코드 갯수 구하기 rs.RecordCount

 

[출처] sunkyun.com/community/bbs/?t=N

배열 변수 Rs.GetRows()

배열은 2차원 배열로 만들어 지며 1차원 값은 원하는 컬럼 값이고 2차원은 컬럼에 해당하는 값이 들어간다.

 

Column 크기 : UBound (배열 변수, 1)

Row 크기 : UBound (배열 변수, 2)

* 배열은 0부터 시작하기 때문에 1 차이가 남


 

sql = "select * from emp"
oraRec.Open sql, oraConn, 1

a_arr   = oraRec.getrows
a_column = ubound(a_arr, 1)
a_row = ubound(a_arr, 2)

response.Write "a_column = " & a_column & "<br/>"
response.Write "a_row = " & a_row & "<br/>"

 

[출처] blog.naver.com/mavis5/10081206806

If문

-- Java, C에서의 if문 사용법
if(조건) {

} else if {

} else {

}

-- ASP에서의 if문 사용법
If 조건 Then
	결과
Else
	결과
End If

※ 보통 if문에서 비교할 때는 '=='으로 비교를 하지만 ASP에서는 '='로 비교를 한다.

※ Else If의 경우 ElseIf로 띄어쓰기 없이 붙여줘야 한다. (EndIf 말고 ElseIf)

 

For문

-- Java, C에서의 for문 사용법
for (int i=0; i<=z; i++) {
	반복될 문장
}

-- ASP에서의 for문 사용법
For i=0 To Z Step 1 
	반복될 문장
Next

 

Do While문

-- Do While문
<%
	a = 1
    
    Do While a < 10	-- a가 10보다 작다면 (조건식이 참이라면)
    	response.write a & "<br>"
        a = a + 1
    Loop
%>

-- Do Until문
<% 
	a = 1
    
    Do Until a > 10  -- a가 10보다 클때까지 (조건식이 거짓이라면)
    	response.write a & "<br>"
        a = a + 1
    Loop
%>

-- Do Loop While문 : 최소 1번 이상 실행 해야 하는 경우에 사용
<%
	a = 1
    
    Do
    	response.write a & "<br>"
        a = a + 1
    Loop while a > 10
%>

ERROR

ORA-12154: TNS:지정된 접속 식별자를 분석할 수 없음


해결방법

시스템변수에 환경변수 2개를 추가

(1) TNS_ADMIN: C:\app\client\사용자이름\product\12.2.0\client_1\Network\Admin

(2) ORACLE_HOME: C:\app\client\사용자이름\product\12.2.0\client_1

 

경로는 오라클이 깔려있는 각자 본인의 파일 경로를 사용

 

 

BOF는 Begin Of File로 레코드 셋의 시작, EOF는 End Of File로 레코드 셋의 끝을 의미한다.

레코드가 하나가 아닌 경우 가상 테이블의 형태로 레코드셋이 저장되고 그 시작과 끝을 구분해주는 것이 BOF와 EOF이다.

 

주로 DB에서 데이터를 불러오는 경우 사용

If Rs.EOF Or Rs.BOF Then
...(중략)
End If

 

DB에 데이터가 있는 경우 Rf.EOF와 RS.BOF는 false가 되고 데이터가 없는 경우 true가 된다.

일반적으로 아래처럼 EOF만 사용해서 데이터를 출력하는 데 많이 사용하고 있다.

If Not Rs.EOF Then
...(출력 데이터)
End If

if rs.BOF or rs.EOF then
  response.write "데이터가 존재하지 않습니다"
else
  response.write "데이터 출력"
end if

[출처] travelpark.tistory.com/51

페이지 단위로 인코딩을 설정하는 방법

이 경우 아래와 같이 코드를 페이지 최상단에 추가한다.

<%@Language="VBScript" CODEPAGE="65001" %>
<%
 
  Response.CharSet="utf-8"
  Session.codepage="65001"
  Response.codepage="65001"
  Response.ContentType="text/html;charset=utf-8"
%>

 

[출처] codelib.tistory.com/28

'프로그램 > ASP' 카테고리의 다른 글

[ASP] If문, For문, Do While문  (0) 2021.03.09
[ASP] BOF와 EOF의 의미  (0) 2021.03.09
[ASP] 기초 문법 실습하기  (0) 2021.03.03
ASP 기본 문법 I  (0) 2021.03.03
ASP 란 무엇인가?  (0) 2021.03.03

+ Recent posts