foreach문은 배열을 순회하면서 각각의 데이터 요소들에 순서대로 접근할 수 있도록 해주는 역할을 한다.

 

문법

foreach (데이터형식 변수명 in 배열) { }

int[] arr = {1, 2, 3, 4, 5, 6};
foreach (int num in arr)
{
	Console.WriteLine(num);
}

 

데이터 형식에는 var도 들어갈 수 있다.

  • var키워드는 암시적 타입 지역 변수를 의미하는데 초기화 문의 오른쪽에 있는 식에서 변수의 형식을 유추하도록 컴파일러에게 지시를 함으로써 명시적 형식을 제공하지 않고 지역 변수를 선언할 수 있다.
  • foreach 초기화문 , for 초기화문, using문에서 사용 가능하다. 
int[] arr = {1, 2, 3, 4, 5, 6};
foreach (var num in arr)
{
	Console.WriteLine(num);
}

 

 

C#에서 Oracle을 엑세스하기 위해서는 .NET에서 제공하는 System.Data.OracleClient.dll를 참조에 추가해야 한다.

우선, Oracle의 데이터를 사용하기 위해서는 Oracle의 데이터베이스에 연결을 해야한다.

 

OracleConnection 클래스

데이터베이스에 대한 열린 연결을 나타낸다. 이 클래스는 상속될 수 없다.

OracleConnection 개체는 범위에서 벗어나도 열려 있는 상태로 유지된다.

즉, 항상 Close 또는 Dispose를 호출하거나 Using문 내에서 OracleConnection 개체를 사용하여 닫아줘야 한다.

 

OracleCommand 클래스

데이터베이스에서 실행한 SQL문 또는 저장 프로시저를 나타낸다. 이 클래스는 상속될 수 없다.

 

항목 설명
ExecuteReader 행을 반환하는 명령을 실행한다.
ExecuteOracleNonQuery Connection에 대해 SQL문을 실행하고 영향 받는 행의 수를 반환한다.
ExecuteNonQuery SQL INSERT, DELETE, UPDATE 및 SET 문과 같은 명령을 실행한다.
ExrcuteScalar 데이터베이스에서 집계 값과 같은 단일 값을 .NET Framework 데이터 형식으로 검색한다.
ExecuteOracleScalar 데이터베이스에서 집계 값과 같은 단일 값을 Oracle 고유 데이터 형식으로 검색한다.

 

1) ExecuteReader를 이용한 데이터베이스의 데이터 읽기 예제

public void ReadData(string connectionString)
{
    string queryString = "SELECT EEMPNO, DEPTNO FROM TABLE";
    using (OracleConnection connection = new OracleConnection(connectionString))
    {
        OracleCommand command = new OracleCommand(queryString, connection);
        connection.Open();
        OracleDataReader reader = command.ExecuteReader();
        try
        {
            while (reader.Read())
            {
                Console.WriteLine(reader.GetInt32(0) + ',' + reader.GetInt32(1));
            }
        }
        finally {
            reader.Close();
        }
    }
}

 

2) ExecuteNonQuery를 이용한 쿼리 명령문 실행 예제

public void InsertRow(string connectionString)
{
    string queryString = "INSERT INTO DEPT(DEPTNO, DNAME,LOC) VALUES (50, 'THCHNOLOGY', 'DENVER')";
    using (OracleConnection connection = new OracleConnection(connectionString))
    {
        OracleCommand command = new OracleCommand(queryString);
        command.Connection = connection;
        try
        {
            connection.Open();
            command.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

 

#region을 사용하면 코드 편집기의 개요 기능을 사용할 때 확장하거나 축소할 수 있는 코드 블록을 지정할 수 있다.

 

설명

#region 블록은 #endregion 지시문으로 종료해야 한다.

#region 블록은 #if 블록과 겹칠 수 없다. 그러나  #region 블록을 #if 블록에 중첩할 수 있고 #if 블록을 #region 블록에 중첩할 수 있습니다.

 

 

 

[출처] docs.microsoft.com/ko-kr/dotnet/csharp/language-reference/preprocessor-directives/preprocessor-region

Unique Key를 생성하는 방법은 DBMS마다 차이가 있다.
MS-SQL은 IDENTITY를, MySQL은 auto_increment,

오라클에서는 Sequence를 사용하여 다음과 같이 유사하게 구현할 수 있다.

 

1. 자동증가컬럼을 사용하고자 하는 MYTABLE테이블을 생성한다.

CREATE TABLE MYTABLE(
	ID NUMBER, NAME VARCHAR2(20)
);

 

2. CREATE SEQUENCE 라는 문장을 사용하여 SEQ_ID라는 이름의 시퀀스를 만든다.

CREATE SEQUENCE SEQ_ID INCREMENT BY 1 START WITH 10000;

-- INCREMENT BY 1 : 증가값은 1
-- START WITH 10000 :  10000부터 증가

 

3.  테이블에 데이터 입력시에는 NEXTVAL이라는 슈도 컬럼(Pseudo-column)을 이용하여 시퀸스를 사용한다.

INSERT INTO MYTABLE VALUES( SEQ_ID.NEXTVAL, '홍길동');

-- CURRVAL : 현재 값을 반환 합니다. .
-- NEXTVAL : 현재 시퀀스값의 다음 값을 반환 합니다.

 

Sequence 구문

 

CREATE SEQUENCE sequence_name
       [START WITH n]
       [INCREMENT BY n]
       [MAXVALUE n | NOMAXVALUE]
       [MINVALUE n | NOMINVALUE]
       [CYCLE | NOCYCLE]

 

* START WITH
시퀀스의 시작 값을 지정합니다. n을 1로 지정하면 1부터 순차적으로 시퀀스번호가 증가 합니다.

* INCREMENT BY
시퀀스의 증가 값을 말합니다. n을 2로 하면 2씩 증가합니다.
START WITH를 1로 하고 INCREMENT BY를 2으로 하면 1, 3, 5,7,..
이렇게 시퀀스  번호가 증가하게 됩니다.

* MAXVALUE n | NOMAXVALUE
MAXVALUE는 시퀀스가 증가할수 있는 최대값을 말합니다.
NOMAXVALUE는 시퀀스의 값을 무한대로 지정합니다.

* MINVALUE n  | NOMINVALUE
MINVALUE는 시퀀스의 최소값을 지정 합니다.
기본값은 1이며, NOMINVALUE를 지정할 경우 최소값은 무한대가 됩니다

 

[사용규칙]

* NEXTVAL, CURRVAL을 사용할 수 있는 경우
   - subquery가 아닌 select문
   - insert문의 select절
   - insert문의 value절
   - update문의 set절

* NEXTVAL, CURRVAL을 사용할 수 없는 경우
   - view의 select절
   - distinct 키워드가 있는 select문
   - group by, having, order by절이 있는 select문
   - select, delete, update의 subquery
   - create table, alter table 명령의 default값

 

[수정]

ALTER SEQUENCE sequence_name
       [INCREMENT BY n]
       [MAXVALUE n | NOMAXVALUE]
       [MINVALUE n | NOMINVALUE]
       [CYCLE | NOCYCLE]

START WITH는 수정할수 없습니다.
START WITH 절이 없다는 점을 빼고는 CREATE SEQUENCE와 같습니다.

 

[삭제]

DROP SEQUENCE sequence_name

 


[출처] https://applejara.tistory.com/260

 

디렉토리 목록 얻어오기 예제

 

[결과 화면]
[실제 파일 목록]

 

코드

<%
	Set fs = Server.CreateObject("Scripting.FileSystemObject")
	Set folderObj = fs.GetFolder(Server.MapPath("."))
	Set files = folderObj.Files
%>

<html>
	<head>
		<title> 파일 리스트 얻기 예제 </title>
	</head>

	<body>
		<h3><%=Server.MapPath(".")%> 디렉토리 목록 </h3>
		<table border="1" width="900" style="font-size:7pt;" cellpadding="2">
			<tr>
				<th>이름</th>
				<th>크기</th>
				<th>형식</th>
				<th>생성 시각</th>
				<th>마지막 엑세스 시간</th>
				<th>마지막 수정 시간</th>
			</tr>
		<%For Each file in files%>
			<tr>
				<td><a href=" <%=file.name%>"><%=file.name%></a></td>
				<td><%=file.size%> byte</td>
				<td><%=file.type%></td>
				<td><%=file.DateCreated%></td>
				<td><%=file.DateLastAccessed%></td>
				<td><%=file.DateLastModified%></td>
			</tr>
		<%Next%>
		</table>
	</body>
</html>

 


DB값 테이블로 출력하기

 

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

 

코드

-- DB연결 해주기

<html>
    <head>
    <title>예제 - DB값 테이블 형태로 출력하기</title>
    </head>
    <body>
      <table border="1" width="400" style="font-size:7pt;" cellpadding="2">
      <tr>
          <th>SEQ</th>
          <th>NAME</th>
          <th>CONTENTS</th>
          <th>REGDATE</th>
      </tr>
      <%Do While Not OraRec.EOF%>
      <tr>
          <td><%=OraRec.Fields("seq")%></td>
          <td><%=OraRec.Fields("name")%></td>
          <td><%=OraRec.Fields("contents")%></td>
          <td><%=OraRec.Fields("regdate")%></td>
      </tr>

      <%OraRec.MoveNext%>
      <%Loop%>
      </table>
    </body>
</html>

 

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

+ Recent posts