Please Enable JavaScript!
Gon[ Enable JavaScript ]

Oracle DB Connection

기타 언어/C# & MFC
반응형
Oracle 뿐만 아니라 모든 DB 접속을 위해서는 ADO.NET Programming 을 해야한다.
이것은 두가지 타입이 존재하는데 DataSet 과 OleDbCommand 이다.
이 둘의 차이점은 Connection 을 유지하느냐 아니냐의 차이이다.
DataSet 은 DB 와 연결하여 데이타를 가져온후 메모리에 저장하고 연결을 끊는다.
OleDbCommand 는 연결을 지속하면서 DB 와 작업을 진행하는 것이다.

각각의 경우는 장단점이 있어서  상황에 따라 적절하게 활용하면 될것이다.
Oracle 과 연결하기 위해서는 local ,PC 에 Oracle client 가 설치되어있어야 하며
연결 문자열에 SID 가 들어가므로 알고 있어야한다.

studio 에서는 프로그램 작성전에 Add References 을 통해서 System.Data.OracleClient 추가해야된다.
그리고 프로그램 클래스 상단에 using System.Data.OracleClient; 를 선언한다.
다음은 Connection 과 select  쿼리 함수, not select 쿼리 함수를 작성한 class 의 소스 이다.

using System;

using System.Data;

using System.Collections.Generic;

using System.Text;

using System.Data.OracleClient;

 

namespace DBManager

{

    class DBConnOracle {

        private OracleConnection conn;

        public DBConnOracle(){

        }

        public bool OpenConnection(string SID, string user, string password) {

            bool bConn = false;

            try {

                //instance new oracle connection

                conn = new OracleConnection("Data Source=" + SID +

                          "; User Id=" + user + "; Password=" + password + ";");

                //open the connection

                conn.Open();

                bConn = true;

            }catch (Exception ex) {

                Console.WriteLine(ex.Message);

                throw;

            }

            return bConn;

        }

        public void execQuery(string sql) {

            OracleCommand cmd = new OracleCommand(sql);

 

            cmd.Connection = conn;

            cmd.CommandType = CommandType.Text;

            try {

                OracleDataReader reader = cmd.ExecuteReader();

                while (reader.Read()){

                   Console.WriteLine(Convert.ToString(reader["MESSAGE_ID"]));

                   Console.WriteLine(Convert.ToString(reader["USERNAME"]));

                   Console.WriteLine(Convert.ToString(reader["MESSAGE"]));

                   Console.WriteLine(Convert.ToString(reader["ID"]));

                }

            }

            catch (Exception ex) {

                Console.WriteLine(ex.Message);

                throw;

            }

            Finally {

                cmd.Dispose();

            }

        }

        public bool execNonQuery(string sql) {

            OracleCommand command = new OracleCommand(sql);

            command.Connection = conn;

            try {

                //a non-query command doesnt need any reader,

                // all you have to do is execute them !

                command.ExecuteNonQuery();

                return true;

            }catch (Exception ex) {

                Console.WriteLine(ex.Message);

                throw;

                return false;

            }

        }

    }

}





반응형
Posted by 녹두장군1
,