[C#] C# 윈폼을 이용하여 MSSQL 연동하는 방법



 

이번 포스팅에서는 C# 윈폼 환경에서 SQL Server 연동하는 방법에 대해서 알아보도록 하겠습니다.


 

지난번 오라클 11g 연동하는 방법에 대해서 글을 쓴 적이 있었는데, 이번 포스팅도 위와 크게 다르지 않기 때문에 아래 내용을 천천히 사진과 설명을 통하여 따라 하시면 쉽게 연동을 하실 수 있을 것이라 생각합니다.


 

저는 SQL Server 2014를 다운받아서 사용하였고, 이 글을 읽으시는 분들도 기본적으로 SQL Server Management Studio가 모두 다운 받아져 있다고 가정하에 글을 쓰도록 하겠습니다.


제일 먼저, 아래와 같이 기본 윈도우 폼 프로젝트를 하나 생성하여 주시기 바랍니다.


그리고 DataGridView 컨트롤을 아래와 같이 배치해 주시기 바랍니다.



(참고로 DataGridView 속성의 Name : DataGridView1)


 

여기까지 하셨다면, 이제 Test할 데이터베이스를 SQL Management Studio에서 하나를 생성해 주시고 아래와 같이 Student 테이블을 생성해 주시기 바랍니다.


(참고로 저 같은 경우는 Database Name : BOEMBOEMJOJO, Table Name : Student)




 

그리고 나서 DBHelper 라는 클래스를 선언하여 아래와 같이 코드를 작성해 주시기 바랍니다.


 

[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

using System;

using System.Collections.Generic;

using System.Data.SqlClient;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

 

namespace ConfigTest

{

    public class DBHelper

    {

        //커넥션 객체

        private static SqlConnection conn = null;

        public static string DBConnString { get; private set; }

 

        public static bool bDBConnCheck = false;

 

        private static int errorBoxCount = 0;

 

        /// <summary>

        /// 생성자

        /// </summary>

        public DBHelper() { }

 

        public static SqlConnection DBConn

        {

            get

            {

                if (!ConnectToDB())

                {

                    return null;

                }

                return conn;

            }

        }

 

        /// <summary>

        /// Database 접속 시도

        /// </summary>

        /// <returns></returns>

        public static bool ConnectToDB()

        {

            if (conn == null)

            {

                //서버명초기 DB인증 방법

                DBConnString = String.Format("Data Source=({0});Initial Catalog={1};Integrated Security={2}; Timeout=3""local""BOEMBOEMJOJO""SSPI"); 

 

                conn = new SqlConnection(DBConnString);

            }

 

            try

            {

                if (!IsDBConnected)

                {

                    conn.Open();

 

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

                    {

                        bDBConnCheck = true;

                    }

                    else

                    {

                        bDBConnCheck = false;

                    }

                }

            }

            catch (SqlException e)

            {

                errorBoxCount++;

                if (errorBoxCount == 1)

                {

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

                }

                return false;

            }

            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

 

그리고 나서 From.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

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Data.SqlClient;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

 

namespace ConfigTest

{

    public partial class Form1 : Form

    {

        private DataTable date_table = null;

 

        public Form1()

        {

            InitializeComponent();

 

            try

            {

                lock (DBHelper.DBConn)

                {

                    if (!DBHelper.IsDBConnected)

                    {

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

                        return;

                    }

                    else

                    {

                        //DB 연결이 되고  ..

                        SqlDataAdapter adapter = new SqlDataAdapter(

"Select * FROM Student", DBHelper.DBConn);

                        date_table = new DataTable();

 

                        try

                        {

                            adapter.Fill(date_table);

                            dataGridView1.DataSource = date_table;

 

                            //DataGridView 사이즈에 맞게 자동 조정

                            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

                        }

                        catch (Exception e)

                        {

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

                        }

                        DBHelper.Close();

                    }

                }

            }

            catch (ArgumentNullException ane)

            {

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

            }

        }

    }

}

 

Colored by Color Scripter

cs

 

 

그리고 실행을 시키시면 아래와 같이 실행 결과 화면이 뜨게 됩니다.


 

[실행 결과 화면]



 

이렇게 해당 데이터베이스와 제대로 연동하여 내용을 DataGridView 에 알맞게 뿌려주는 것을 확인할 수 있습니다.


천천히 따라하시면 누구나 쉽게 적용 하실거라 생각합니다~~

 

감사합니다.^^


728x90

이 글을 공유하기

댓글

Designed by JB FACTORY