[윈폼] 윈폼 로그인 및 회원가입 UI 구성 및 기능 구현 (Oracle 연동)


 

안녕하세요~~

 

오늘은 윈폼과 오라클을 연동하여 로그인 및 회원가입 화면 UI 구성 및 기능 구현이 되는 예제를 작성해 보도록 할게요.


1. 오라클에서 회원 테이블 생성


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

CREATE TABLE WIN.EMPLOYEE

(

  ID VARCHAR2(500 BYTE),

  PASSWORD VARCHAR2(500 BYTE),

  ENAME  VARCHAR2(50 BYTE),

  EAGE   VARCHAR2(20 BYTE),

  PHONENUMBER VARCHAR2(500BYTE)

)

TABLESPACE USERS

PCTUSED    0

PCTFREE    10

INITRANS   1

MAXTRANS   255

STORAGE    (

            INITIAL          64K

            NEXT             1M

            MINEXTENTS       1

            MAXEXTENTS       UNLIMITED

            PCTINCREASE      0

            BUFFER_POOL      DEFAULT

           )

LOGGING 

NOCOMPRESS 

NOCACHE

NOPARALLEL

MONITORING;

 

Colored by Color Scripter

cs

 

위의 쿼리를 실행 시키면 아래와 같이 Employee 테이블이 생성 됩니다.

 

Employee Table





 

2. 윈폼 UI 구성


- Login 화면



1

txt_ID

2

txt_PW

3

btn_Register

4

btn_login

 


- 회원가입 화면



1

txt_ID

2

txt_PW

3

txt_Name

4

txt_Age

5

txt_Phone

6

btn_Register

 

여기까지 모두 따라하셨다면 UI 작업은 마무리 된 것입니다.

이제는 실제 회원가입, 로그인 기능을 구현 하도록 하겠습니다.

 

(참고로, 오라클 연동 소스는 올리기만 하고 따로 설명을 드리지 않겠습니다. 이전에 따로 포스팅을 했기 때문에 해당 소스 그대로 사용하여 진행했습니다.)

 


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


 


DB 연동 소스 코드


[OracleDBManager.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

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

using Oracle.DataAccess.Client;

using System;

using System.Collections.Generic;

using System.Data;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace Login

{

    public sealed class OracleDBManager

    {

        public string ConnectionString = string.Empty;

        public string Address = string.Empty;

        public string Port = string.Empty;

 

        private OracleCommand LastExecutedCommand = null;

        private int RetryCnt = 0;

 

        public OracleConnection Connection { get; private set; }

 

        public bool GetConnection()

        {

            try

            {

                if (this.Connection != null)

                {

                    this.Connection.Close();

                    this.Connection.Dispose();

                    this.Connection = null;

                }

 

                if (ConnectionString == string.Empty)

                    SetConnectionString();

 

                Connection = new OracleConnection(ConnectionString);

 

                if (this.Address != string.Empty)

                    Connection.Open();

            }

            catch (Exception ex)

            {

                System.Reflection.MemberInfo info = System.Reflection.MethodInfo.GetCurrentMethod();

                string id = string.Format("{0}.{1}", info.ReflectedType.Name, info.Name);

 

                if (this.ExceptionEvent != null)

                    this.ExceptionEvent(id, ex);

 

                return false;

            }

 

            if (Connection.State == ConnectionState.Open)

                return true;

            else

                return false;

        }

 

        #region private..........................................................

 

        private void SetConnectionString()

        {

            string user = ConfigManager.GetValue("DATABASE""USER");

            string pwd = ConfigManager.GetValue("DATABASE""PWD");

            string port = ConfigManager.GetValue("DATABASE""PORT");

            string sid = ConfigManager.GetValue("DATABASE""SID");

            string svr = ConfigManager.GetValue("DATABASE""SERVICE_NAME");

            string addr01 = ConfigManager.GetValue("DATABASE""D_ADDR01");

            string addr02 = ConfigManager.GetValue("DATABASE""D_ADDR02");

 

            string address01 = string.Format("(ADDRESS = (PROTOCOL = TCP)

(HOST = {0})(PORT = {1}))", addr01, port);

            string address02 = string.Format("(ADDRESS = (PROTOCOL = TCP)

(HOST = {0})(PORT = {1}))", addr02, port);

 

            string dataSource = string.Format(@"(DESCRIPTION =(ADDRESS_LIST 

={0}{1})(CONNECT_DATA =(", address01, address02);

 

            dataSource += svr == string.Empty ? string.Format("SID = {0})))",

 sid) : string.Format("SERVICE_NAME = {0})))", svr);

 

            this.Address = addr01;

            this.Port = port;

            this.ConnectionString = "User Id=" + user + ";Password=" + pwd + ";Data Source=" + dataSource;

        }

 

        private bool CheckDBConnected()

        {

            string query = "SELECT 1 FROM DUAL";

            OracleDataReader result = null;

 

            try

            {

                OracleCommand cmd = new OracleCommand();

                cmd.Connection = this.Connection;

                cmd.CommandText = query;

                result = cmd.ExecuteReader();

            }

            catch { }

 

            if (result != null && result.HasRows)

                return true;

 

            return false;

        }

 

        public int ExecuteNonQuery(string query, params object[] oParams)

        {

            lock (this)

            {

                RetryCnt = 0;

 

                int result = Execute_NonQuery(query);

 

                return result;

            }

        }

 

        public DataSet ExecuteDsQuery(DataSet ds, string query)

        {

            ds.Reset();

 

            lock (this)

            {

                RetryCnt = 0;

 

                return ExecuteDataAdt(ds, query);

            }

        }

 

        private DataSet ExecuteDataAdt(DataSet ds, string query)

        {

            try

            {

                OracleDataAdapter cmd = new OracleDataAdapter();

                cmd.SelectCommand = new OracleCommand();

                cmd.SelectCommand.Connection = this.Connection;

                cmd.SelectCommand.CommandText = query;

 

                LastExecutedCommand = cmd.SelectCommand;

                cmd.Fill(ds);

            }

            catch (Exception ex)

            {

                //연결 해제 여부 확인  해제  재연결  다시 시도...

                if (RetryCnt < 1 && CheckDBConnected() == false)

                {

                    RetryCnt++;

 

                    GetConnection();

 

                    Exception ex02 = new Exception("Reconnect to database");

 

                    if (this.ExceptionEvent != null)

                        this.ExceptionEvent(string.Empty, ex02);

 

                    ds = ExecuteDataAdt(ds, query);

                    return ds;

                }

 

                System.Reflection.MemberInfo info = 

System.Reflection.MethodInfo.GetCurrentMethod();

                string id = string.Format("{0}.{1}\n[{2}]",

 info.ReflectedType.Name, info.Name, query);

 

                if (this.ExceptionEvent != null)

                    this.ExceptionEvent(id, ex);

 

                this.LastExceptionString = ex.Message;

 

                return null;

            }

 

            return ds;

        }

 

        private int Execute_NonQuery(string query)

        {

            int result = 0;

 

            try

            {

                OracleCommand cmd = new OracleCommand();

                cmd.Connection = this.Connection;

                cmd.CommandText = query;

 

                LastExecutedCommand = cmd;

                result = cmd.ExecuteNonQuery();

            }

            catch (Exception ex)

            {

                //연결 해제 여부 확인  해제  재연결  다시 시도...

                if (RetryCnt < 1 && CheckDBConnected() == false)

                {

                    RetryCnt++;

 

                    GetConnection();

 

                    result = Execute_NonQuery(query);

                    return result;

                }

 

                System.Reflection.MemberInfo info = 

System.Reflection.MethodInfo.GetCurrentMethod();

                string id = string.Format("{0}.{1}\n[{2}]"

info.ReflectedType.Name, info.Name, query);

 

                result = -1;

            }

 

            return result;

        }

 

        #endregion private..................................................................

    }

}

 

Colored by Color Scripter

cs

 

[ConfigManager.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

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Xml.Linq;

 

namespace Login

{

    public class ConfigManager

    {

        private static string configFileName = @"Config.xml";

        public static string GetValue(params string[] args)

        {

            string result = string.Empty;

 

            try

            {

                XDocument xDoc = XDocument.Load(configFileName);

                result = GetNodeValue(xDoc.FirstNode as XElement, 0, args);

            }

            catch (Exception ex)

            {

                result = ex.Message;

                result = string.Empty;

            }

 

            return result;

        }

 

        private static string GetNodeValue(XElement node, int idx, params string[] args)

        {

            string result = string.Empty;

 

            if (args.Length > idx + 1)

                result = GetNodeValue(node.Element(args[idx]), ++idx, args);

            else

                result = node.Element(args[idx]).Value.ToString();

 

            return result;

        }

    }

}

 

Colored by Color Scripter

cs

 

[Config,xml]


1

2

3

4

5

6

7

8

9

10

11

<Configuration>

  <DATABASE>

    <D_ADDR01>127.0.0.1</D_ADDR01>

    <D_ADDR02>127.0.0.1</D_ADDR02>

    <PORT>1521</PORT>

    <USER>WIN</USER>

    <PWD>dnlsvh</PWD>

    <SERVICE_NAME>ORCL</SERVICE_NAME>

  </DATABASE>

</Configuration>

 

Colored by Color Scripter

cs

 

[Program.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

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using System.Windows.Forms;

 

namespace Login

{

    static class Program

    {

        /// <summary>

        /// 해당 응용 프로그램의  진입점입니다.

        /// </summary>

        [STAThread]

        static void Main()

        {

            OracleDBManager dbManager = new OracleDBManager();

 

            if (dbManager.GetConnection() == false)

            {

                MessageBox.Show("데이터 베이스 접속 연결 실패!!!!!");

                return;

            }

 

            Application.EnableVisualStyles();

            Application.SetCompatibleTextRenderingDefault(false);

            Application.Run(new Form1());

        }

    }

}

 

Colored by Color Scripter

cs

 

Program.cs에서 오라클 Connection을 시도해줍니다. 그래서 연결이 실패하면 연결 실패라는 메시지 창이 뜨게 하고, 연결이 성공했으면 MainForm이 제대로 실행 되도록 코드를 작성하였습니다.

 

회원가입 폼 소스 코드


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

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;

 

namespace Login

{

    public partial class Register : Form

    {

        public Register()

        {

            InitializeComponent();

 

            //버튼 클릭 이벤트 선언

            this.btn_Register.Click += Btn_Click;

        }

 

        //버튼 클릭 이벤트 핸들러

        public void Btn_Click(object sender, EventArgs e)

        {

            InserEmployeeData();

        }

 

        /// <summary>

        /// INSERT 쿼리 수행 구문

        /// </summary>

        public void InserEmployeeData()

        {

            DataSet ds = new DataSet();

            string query = string.Empty;

            OracleDBManager db = new OracleDBManager();

 

            string id = string.Empty;

            string pw = string.Empty;

            string name = string.Empty;

            string age = string.Empty;

            string phoneNumber = string.Empty;

 

            id = txt_ID.Text;

            pw = txt_PW.Text;

            name = txt_Name.Text;

            age = txt_Age.Text;

            phoneNumber = txt_Phone.Text;

 

            query = @"

            INSERT INTO WIN.EMPLOYEE 

            VALUES ('#ID', '#PW', '#NAME', '#AGE', '#PHONE')

            ";

 

            query = query.Replace("#ID", id);

            query = query.Replace("#PW", pw);

            query = query.Replace("#NAME", name);

            query = query.Replace("#AGE", age);

            query = query.Replace("#PHONE", phoneNumber);

 

            int result = db.ExecuteNonQuery(query);

 

            if(result > 0)

            {

                MessageBox.Show("회원 가입 성공");

            }

        }

    }

}

 

Colored by Color Scripter

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;

 

namespace Login

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

 

            //버튼 클릭 이벤트 선언

            this.btn_login.Click += Btn_LoginClick;

            this.btn_Register.Click += Btn_RegisterClick;

        }

 

        /// <summary>

        /// 로그인 버튼 클릭 이벤트 핸들러

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        public void Btn_LoginClick(object sender, EventArgs e)

        {

            DataSet ds = new DataSet();

            OracleDBManager db = new OracleDBManager();

            string id = txt_ID.Text;

            string pwd = txt_PW.Text;

 

            string query = @"

SELECT ID, PASSWORD

FROM WIN.EMPLOYEE

WHERE 1 = 1

AND ID = '#ID'

AND PASSWORD = '#PW'

";

 

            query = query.Replace("#ID", id);

            query = query.Replace("#PW", pwd);

 

            db.ExecuteDsQuery(ds, query);

 

            if(ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)

            {

                MessageBox.Show("로그인 성공");

            }

            else

            {

                MessageBox.Show("로그인 실패");

            }

        }

 

        /// <summary>

        /// 회원가입 버튼 클릭 이벤트 핸들러

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        public void Btn_RegisterClick(object sender, EventArgs e)

        {

            Register fm1 = new Register();

            fm1.ShowDialog();

        }

    }

}

 

Colored by Color Scripter

cs

 

여기까지 모두 작성 하셨다면 이제 회원가입 및 로그인 기능 구현은 모두 완료한 것입니다.

 

실행 결과


1.  회원가입




2.  DB 데이터 저장 성공




3.  로그인 시도


 

이로써 윈폼과 오라클을 연동하여 간단한 회원가입 및 로그인 기능 구현을 해보았습니다.

 

감사합니다!


728x90

이 글을 공유하기

댓글

Designed by JB FACTORY