글로벌 객체지향 프로그래밍 과제 - MySQL과 C# 연결하기
목차
- 구현내용
- SQL 설정하기
- C#에서 연결하기
- 시연
구현내용:
- Mysql 을 사용해 데이터 베이스를 구축
- C#을 이용해서 테이블에서 데이터를 가져오고 수정하는 ( Select , Insert, Update ) 코드 구현
SQL 설정하기
SQL은 다음과 같이 구성하였다
기본값은 아래의 값 2개만 추가하였다
C#에서 연결하기
전체 코드는 다음과 같다
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
217
218
219
220
221
222
223
using MySql.Data.MySqlClient;
using System.ComponentModel;
using System.Diagnostics;
namespace Money_Wiring_Test_Prj
{
class Money_Wiring_Test_Prj
{
static void Main(string[] args)
{
var sqlLogin = new MySQL_Login("localhost", "bank_db", "root", "0000");
while (!sqlLogin.isLoginSucceed)
{
Console.Write("로그인을 진행합니다. \n ID를 입력 해주세요 : ");
var id = Console.ReadLine();
Console.Write("비밀번호를 입력 해주세요 : ");
var pw = Console.ReadLine();
sqlLogin.UserLogin("bank_customer", id, pw);
}
}
}
class MySQL_Login
{
MySqlConnection connection;
//MySQL에 명령어 전송용
MySqlCommand sqlCommand;
MySqlDataReader mySqlDataReader;
/// <summary>
/// 유저 로그인 성공 확인용
/// </summary>
public bool isLoginSucceed;
/// <summary>
/// 송금할 계좌 존재 확인용
/// </summary>
bool isAccountExist;
string selectQuery;
string id;
//General_Login general;
//MySQL DB 연결 생성자
/// <summary>
/// 서버 이름, 데이버베이스이름, 마스터ID, 마스터PW
/// </summary>
/// <param name="ServerName"></param>
/// <param name="DataBase"></param>
/// <param name="userid"></param>
/// <param name="userpw"></param>
public MySQL_Login(string ServerName, string DataBase, string userid, string userpw)
{
try
{
//DB Open
connection = new MySqlConnection("Server=" + ServerName + ";Database=" + DataBase + ";Uid=" + userid + ";Pwd=" + userpw);
connection.Open();
//연결이 성공하였을 경우 DB연결 성공 실패하였을 경우 DB 연결 실패
if (connection.Ping())
Console.WriteLine("DB Master 연결 성공");
//DB 닫기
//connection.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public bool UserLogin(string tableName, string ID, string PW)
{
try
{
id = ID;
if (connection.State == System.Data.ConnectionState.Closed)
connection.Open();
selectQuery = "SELECT * FROM " + tableName + " WHERE id = \'" + ID + "\' ";
sqlCommand = new MySqlCommand(selectQuery, connection);
//ExecuteReader를 통해 입력값을 받고, 해당정보를 mySQLDataReader에 저장
mySqlDataReader = sqlCommand.ExecuteReader();
while (mySqlDataReader.Read())
{
if (ID == (string)mySqlDataReader["id"] && PW == (string)mySqlDataReader["pw"])
isLoginSucceed = true;
else
isLoginSucceed = false;
}
connection.Close();
if (isLoginSucceed)
{
Console.WriteLine("유저 로그인 성공");
AccountCheck();
}
else
Console.WriteLine("유저 로그인 실패");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return isLoginSucceed;
}
void AccountCheck()
{
while (!isAccountExist)
{
try
{
Console.Write("송금할 계좌의 ID를 입력해주세요 : ");
var accountID = Console.ReadLine();
if (connection.State == System.Data.ConnectionState.Closed)
connection.Open();
selectQuery = "SELECT * FROM bank_customer WHERE id = \'" + accountID + "\' ";
sqlCommand = new MySqlCommand(selectQuery, connection);
//ExecuteReader를 통해 입력값을 받고, 해당정보를 mySQLDataReader에 저장
mySqlDataReader = sqlCommand.ExecuteReader();
while (mySqlDataReader.Read())
{
if (accountID == (string)mySqlDataReader["id"])
{
isAccountExist = true;
connection.Close();
Console.Write("계좌가 확인되었습니다. \n 송금할 금액을 입력해주세요 : ");
var wiringAmount = Console.ReadLine();
BalanceWiring(accountID, int.Parse(wiringAmount));
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
//이쪽부터 오류
void BalanceWiring(string accountID, int amount)
{
BalanceUpdate(id, amount, false);
BalanceUpdate(accountID, amount, true);
Console.WriteLine("송금 완료 이후 잔액은 " + GetCurrentBalance(id) + " 입니다");
}
string GetCurrentBalance(string ID)
{
string outputText = null;
if (connection.State == System.Data.ConnectionState.Closed)
connection.Open();
try
{
var selectQuery = "SELECT Balance FROM bank_customer WHERE ID ='" + ID + "\' ";
sqlCommand = new MySqlCommand(selectQuery, connection);
//ExecuteReader를 통해 입력값을 받고, 해당정보를 mySQLDataReader에 저장
mySqlDataReader = sqlCommand.ExecuteReader();
while (mySqlDataReader.Read())
outputText = mySqlDataReader["Balance"].ToString();
mySqlDataReader.Close();
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return outputText;
}
void BalanceUpdate(string ID, int amount, bool isPlus)
{
int calculated_balanced = 0;
if (isPlus)
calculated_balanced = int.Parse(GetCurrentBalance(ID)) + amount;
else
calculated_balanced = int.Parse(GetCurrentBalance(ID)) - amount;
if (connection.State == System.Data.ConnectionState.Closed)
connection.Open();
try
{
var query =
"Update bank_customer " +
" Set Balance= '" + calculated_balanced +
"' Where ID = '" + ID + "';";
sqlCommand = new MySqlCommand(query, connection);
sqlCommand.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
데이터 가져오기
데이터 업데이트하기
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.

