Programming

(C#) 오라클 DB 연결 예제

steloflute 2012. 5. 28. 09:34

http://www.hoons.kr/board.aspx?Name=cshaptip&BoardIdx=27138&Page=1&Mode=2 

 

를 참고하여

 

using System;
using System.Data;
using System.Data.OleDb;


namespace OracleTest {
    class Program {
        private static void Main(string[] args) {
            Console.Write("Data Source: ");
            string dataSource = Console.ReadLine();
            Console.Write("User ID: ");
            string userID = Console.ReadLine();
            Console.Write("Password: ");
            string password = Console.ReadLine();

            string sql = string.Format("Provider=MSDAORA.1;Password={0};User ID={1};Data Source={2};Persist Security Info=True", password, userID, dataSource);     //oracle 서버 연결

            OleDbConnection conn = new OleDbConnection(sql);
            //conn.ConnectionString = sql;
            try {
                conn.Open();            //데이터베이스 연결
                Console.Write("Table: ");
                string table = Console.ReadLine();

                OleDbCommand cmd = new OleDbCommand();
                cmd.CommandText = string.Format("select * from {0}", table);
                cmd.CommandType = CommandType.Text;         //검색명령을 쿼리 형태로

                cmd.Connection = conn;

                OleDbDataReader read = cmd.ExecuteReader(); //select 결과
                Console.WriteLine("***** 테이블 분석 결과 *****");
                for (int i = 0; i < read.FieldCount; i++) {
                    Console.WriteLine("필드이름 : {0} \n", read.GetName(i));
                }
                Console.WriteLine("총필드 개수는" + read.FieldCount);
                read.Close();
            } catch (Exception ex) {
                Console.WriteLine("에러발생{0}", ex.Message);
            } finally {
                if (conn != null) {
                    conn.Close();       //데이터베이스 연결 해제
                    Console.WriteLine("데이터베이스 연결 해제..");
                }
            }
            Console.ReadKey();
        }
    }
}