C# 윈폼을 이용하여 Oracle(오라클) 11g 연동 하는 방법


 

이번 포스팅에서는 C# 윈폼을 이용하여 데이터베이스 중 하나인 Oracle 과 연동하는 방법에 대해서 알아보도록 하겠습니다


우선 Oracle과 연동을 하기 위해서는 총 5개의 dll을 참조 하여야 합니다.

 

Oci.dll

Ociw32.dll

Oracle.DataAccess.dll

oraociei11.dll

OraOps11w.dll

 

이렇게 위와 같은 dll들을 미리 참조 하여야 합니다. 그렇지 않는다면 향후에 프로그램을 실행 시켰을 경우, 형식 이니셜라이저에서 예외를 throw했습니다. 라는 에러 문구를 접하시게 될 것입니다.

 

그러면 이제 간단히 C# 윈폼을 이용하여 실제 어떻게 Oracle과 연동을 하는지 아래 코드를 통하여 살펴 보도록 하겠습니다.

우선 아래와 같이 빈 폼에 DataGridView 컨트롤을 배치시켜 주시기 바랍니다.



 

그리고 나서 DBHelper.cs 클래스를 선언하여 DB연동과 관련한 코드들을 작성해 줍니다.

 

[DBHelper.cs]


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using Oracle.DataAccess.Client;

using System.Windows.Forms;

 

namespace Test.DB

    public class DBHelper

    {

        //커넥션 객체

        private static OracleConnection conn = null;

        public static string DBConnString

        {

            get;

            private set;

        }

 

       // public delegate void FormSendConneckChHandler(bool bConnCheck);

       // public static event FormSendConneckChHandler FormSendConnectCheckEvent;

        public static bool bDBConnCheck = false;

 

        private static int errorBoxCount = 0;

 

        /// <summary>

        /// 생성자

        /// </summary>

        public DBHelper() {}

 

         public static OracleConnection DBConn

        {

            get

            {

                if (!ConnectToDB())

                {

                    return null;

                }

                return conn;

            }

        }

 

        /// <summary>

        /// Database 접속 시도

        /// </summary>

        /// <returns></returns>

        public static bool ConnectToDB()

        {

            if (conn == null)

            {

                DBConnString = String.Format("Data Source=(DESCRIPTION="

              + "(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=LOCALHOST)(PORT=1521)))"

              + "(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=ORCL)));"

              + "User Id=test;Password=1234");

 

                conn = new OracleConnection(DBConnString);

            }

 

            try

            {

                if (!IsDBConnected)

                {

                    conn.Open();

 

                    if (conn.State == System.Data.ConnectionState.Open)

                    {

                        bDBConnCheck = true;   

                    }

                    else

                    {

                        bDBConnCheck = false;

                    }

                }

            }

            catch (Exception e)

            {

                errorBoxCount++;

                if (errorBoxCount == 1)

                {

                    MessageBox.Show(e.Message, "DBHelper - ConnectToDB()");   

                }

               // FormSendConnectCheckEvent(bDBConnCheck);

                return false;

            }

            //FormSendConnectCheckEvent(bDBConnCheck);

            return true;

        }

 

        /// <summary>

        /// Database Open 여부 확인

        /// </summary>

        public static bool IsDBConnected

        {

            get

            {

                if (conn.State != System.Data.ConnectionState.Open)

                {

                    return false;

                }

                return true;

            }

        }

 

        /// <summary>

        /// Database 해제

        /// </summary>

        public static void Close()

        {

            if(IsDBConnected)

                DBConn.Close();

        }

    }

}

 

Colored by Color Scripter

cs

 

참고로 앞에서 말씀 드렸듯이 아래와 같은 dll들을 미리 참조 하셔야 합니다. (해당 dll은 제가 첨부자료로 올려 놓도록 하겠습니다.)




그리고 나서 Form.cs 에 아래와 같이 코드를 작성하여 실행 시켜 주시면 해당 데이터 베이스가 제대로 연결 되었는지 확인 하실 수 있습니다.


 

[Form.cs]


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

using Oracle.DataAccess.Client;

using Test.DB;

 

namespace Test

{

    public partial class Form1 : Form

    {

        static int errorBoxCount = 0;

 

        public Form1()

        {

            InitializeComponent();

        }

 

        private void Form1_Load(object sender, EventArgs e)

        {

            //conn = new OracleConnection(connect_info);

            //cmd = new OracleCommand();

            //conn.Open();

            //cmd.Connection = conn;

            try

            {

                lock (DBHelper.DBConn)

                {

                    if (!DBHelper.IsDBConnected)

                    {

                        MessageBox.Show("Database 연결을 확인하세요.");

                        return;

                    }

                    else

                    {

                        string sql = "SELECT * FROM Test";

                        //DB 연결이 되고  ...

                        OracleDataAdapter adapter = new OracleDataAdapter(sql, DBHelper.DBConn);

                        DataTable date_table = new DataTable();

 

                        try

                        {

                            adapter.Fill(date_table);

                            dataGridView.DataSource = date_table;

                        }

                        catch (System.Exception ex)

                        {

                            

                        }

 

                        DBHelper.Close();

                    }

                }

            }

            catch (ArgumentNullException ane)

            {

                errorBoxCount++;

                if (errorBoxCount == 1)

                {

                    MessageBox.Show(ane.Message, "DataGridView_Load Error");

                }

            }

        }

    }

}

 

Colored by Color Scripter

cs

 

 

[현재 데이터 베이스 Test 테이블 데이터]



 

[실행 결과 화면]



 

위와 같이 폼이 로드 되면서, 해당 테이블에 있는 값들을 제대로 조회하여 DataGridView에 보여주는 것을 확인 하실 수 있습니다.

 

이로써, 간단히 C#과 오라클 간단 연동 방법에 대해서 알아 보았습니다.


참고 - 위의 5개의 Dll 없이도 오라클 연동 하는 방법에 대해서 글을 올렸으니까, 이것도 봐주세요ㅎㅎ

(오라클 연동 URL - https://afsdzvcx123.tistory.com/244)


 

감사합니다.^^


728x90

이 글을 공유하기

댓글

Designed by JB FACTORY