[C# 윈폼] C# 윈폼 CSV 파일 읽고 CSV 내용 DataBase(데이터베이스) Insert(저장) 하기

안녕하세요.

 

오늘은 어제의 이어서 CSV 파일 읽고, 해당 내용을 이번에는 DataBase(데이터베이스) Insert 하여 테이블에 저장까지 하는 방법에 대해서 알려 드리려고 합니다.

 

어제는 단순히 CSV 파일 내용을 읽어서 DataGridView에 바인딩 했던 것 뿐이고, 오늘은 거기에 추가로 DB와 연동하여 테이블에 데이터 저장까지 되도록 프로그램을 만들어 보도록 하겠습니다.

 

그럼 빈 윈폼 프로젝트를 만들어 주시고 아래와 같이 컨트롤을 배치해 주시기 바랍니다.

 

빈 윈폼 프로젝트 생성 및 컨트롤 배치

 

이제 여기서 “CSV Read” 버튼을 클릭하면 DataGridView 컨트롤에 데이터가 바인딩해서 보여지는 기능을 추가할 것이고, “DB Insert” 버튼을 클릭하면 CSV 내용을 읽어서 특정 테이블에 데이터를 Insert 하게 끔 프로그램을 구현 시켜 보도록 하겠습니다.

 

참고로 저는 MSSQL과 연동을 하고 아래와 같이 STUDENT 테이블을 만들어서 해당 테이블에 데이터를 INSERT 해보도록 하겠습니다.

 

STUDENT 테이블

위에 dbo.STUDENT 테이블을 만들어 놨습니다.

 

그럼 이제 예제 코드를 작성해서 DB 연동 및 DB Insert 까지 모두 구현해 보도록 하겠습니다.

 

이번에는 DB 연동 부분 소스코드도 있어서 Class가 많이 있습니다.

 

하나하나 차근차근 모두 작성해 주시기 바랍니다.

 

먼저 완성된 프로젝트 Class는 아래와 같습니다.

 

모든 프로젝트 Class

 

이제 위의 Class들의 소스코드들을 보여 드리도록 하겠습니다.

 

Singleton.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace MSSQL_Connect_Program.Class
{
    public class Singleton<T> where T : classnew()
    {
        private static object _syncobj = new object();
        private static volatile T _instance = null;
        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_syncobj)
                    {
                        if (_instance == null)
                        {
                            _instance = new T();
                        }
                    }
                }
                return _instance;
            }
        }
 
        public delegate void ExceptionEventHandler(string LocationID, Exception ex);
    }
}
 
 
cs

 

SqlDBManager.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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
 
namespace MSSQL_Connect_Program.Class
{
    public sealed class SqlDBManager
    {
        public enum ExcuteResult { Fail = -2, Success };
 
        public string ConnectionString = string.Empty;
 
        public string Address { get; private set; }
        public string LastException { get; private set; }
 
        public SqlConnection Connection { get; private set; }
 
        private static SqlDBManager instance;
 
        public static SqlDBManager Instance
        {
            get
            {
                if (instance == null) instance = new SqlDBManager();
 
                return instance;
            }
        }
 
        private SqlCommand _sqlCmd = null;
 
        public SqlDBManager()
        {
            _sqlCmd = new SqlCommand();
        }
 
        public bool GetConnection()
        {
            try
            {
                if (ConnectionString == string.Empty)
                    SetConnectionString();
 
                Connection = new SqlConnection(ConnectionString);
 
                Connection.Open();
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}\r\nMessage : {1}", ex.StackTrace, ex.Message);
 
                LastException = ex.Message;
 
                return false;
            }
 
            if (Connection.State == ConnectionState.Open)
                return true;
            else
                return false;
        }
 
        public int ExecuteNonQuery(string query)
        {
            lock (this)
            {
                return Execute_NonQuery(query);
            }
        }
 
        public bool HasRows(string query)
        {
            lock (this)
            {
                SqlDataReader result = ExecuteReader(query);
 
                return result.HasRows;
            }
        }
 
        public SqlDataReader ExecuteReaderQuery(string query)
        {
            lock (this)
            {
                SqlDataReader result = ExecuteReader(query);
 
                return result;
            }
        }
 
        public DataSet ExecuteDsQuery(DataSet ds, string query)
        {
            ds.Reset();
 
            lock (this)
            {
                //dbLoger.WriteLog(LogType.Inform, string.Format("ExecuteDsQuery - {0}", query));
 
                return ExecuteDataAdt(ds, query);
            }
        }
 
        public DataSet ExecuteProcedure(DataSet ds, string procName, params string[] pValues)
        {
            lock (this)
            {
                return ExecuteProcedureAdt(ds, procName, pValues);
            }
        }
 
        public void CancelQuery()
        {
            _sqlCmd.Cancel();
        }
 
        public void Close()
        {
            Connection.Close();
        }
 
        #region private..........................................................
 
        [DllImport("wininet.dll")]
        private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);
 
        private bool CheckConnection()
        {
            bool result = true;
 
            if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() == false)
            {
                this.LastException = "네트워크 연결이 끊어졌습니다.";
                System.Windows.Forms.MessageBox.Show(this.LastException, "Error");
                result = false;
            }
            else if (this.Connection == null || this.Connection.State == ConnectionState.Closed)
            {
                result = this.GetConnection();
            }
 
            return result;
        }
 
        private void SetConnectionString()
        {
            string user = XmlManager.GetValue("DATABASE""USER");
            string pwd = XmlManager.GetValue("DATABASE""PWD");
            string svr = XmlManager.GetValue("DATABASE""SERVICE_NAME");
            string addr01 = XmlManager.GetValue("DATABASE""D_ADDR01");
            string addr02 = XmlManager.GetValue("DATABASE""D_ADDR02");
 
            string dataSource = string.Format(@"Data Source={0};Database={1};User Id={2};Password={3}", addr01, svr, user, pwd);
 
            this.Address = addr01;
            this.ConnectionString = dataSource;
        }
 
        private int Execute_NonQuery(string query)
        {
            int result = (int)ExcuteResult.Fail;
 
            try
            {
                _sqlCmd = new SqlCommand();
                _sqlCmd.Connection = this.Connection;
                _sqlCmd.CommandText = query;
                result = _sqlCmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}\r\nMessage : {1}", ex.StackTrace, ex.Message);
 
                LastException = ex.Message;
 
                if (CheckConnection() == falsereturn result;
            }
 
            return result;
        }
 
        private SqlDataReader ExecuteReader(string query)
        {
            SqlDataReader result = null;
 
            try
            {
                _sqlCmd = new SqlCommand();
                _sqlCmd.Connection = this.Connection;
                _sqlCmd.CommandText = query;
                result = _sqlCmd.ExecuteReader();
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}\r\nMessage : {1}", ex.StackTrace, ex.Message);
 
                LastException = ex.Message;
 
                if (CheckConnection() == falsereturn result;
            }
 
            return result;
        }
 
        private DataSet ExecuteDataAdt(DataSet ds, string query)
        {
            try
            {
                SqlDataAdapter cmd = new SqlDataAdapter();
                cmd.SelectCommand = _sqlCmd;
                cmd.SelectCommand.Connection = this.Connection;
                cmd.SelectCommand.CommandText = query;
                cmd.Fill(ds);
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}\r\nMessage : {1}", ex.StackTrace, ex.Message);
 
                LastException = ex.Message;
 
                if (CheckConnection() == falsereturn null;
            }
 
            return ds;
        }
 
        private DataSet ExecuteProcedureAdt(DataSet ds, string query, params string[] values)
        {
            try
            {
                SqlDataAdapter adapter = new SqlDataAdapter();
                adapter.SelectCommand = _sqlCmd;
                adapter.SelectCommand.CommandText = query;
                adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
                adapter.SelectCommand.Connection = this.Connection;
 
                for (int i = 0; i < values.Length; ++i)
                {
                    adapter.SelectCommand.Parameters.Add(values[i]);
                    //adapter.SelectCommand.Parameters.Add("params", values[i]);
                }
 
                adapter.Fill(ds);
 
                return ds;
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}\r\nMessage : {1}", ex.StackTrace, ex.Message);
 
                this.LastException = ex.Message;
 
                if (CheckConnection() == falsereturn null;
            }
 
            return ds;
        }
 
        #endregion private..................................................................
    }
}
 
 
cs

 

XmlManager.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
 
namespace MSSQL_Connect_Program.Class
{
    public class XmlManager : Singleton<XmlManager>
    {
        #region " Properties & Variables "
 
        private static string configFile = @"Config.xml";
        public static string ConfigFile { get { return configFile; } set { configFile = value; } }
 
        #endregion " Properties & Variables End"
 
        #region "  Public methode "
 
        public static string GetValue(params string[] args)
        {
            string result = string.Empty;
 
            try
            {
                XDocument xDoc = XDocument.Load(configFile);
                result = GetNodeValue(xDoc.FirstNode as XElement, 0, args);
            }
            catch (Exception ex)
            {
                result = ex.Message;
                result = string.Empty;
            }
 
            return result;
        }
 
        public static bool SetValue(params string[] args)
        {
            bool result = false;
 
            try
            {
                XDocument xDoc = XDocument.Load(configFile);
 
                result = SetNodeValue(xDoc.FirstNode as XElement, 0, args);
 
                xDoc.Save(configFile);
            }
            catch
            {
                result = false;
            }
 
            return result;
        }
 
        #endregion "  Public methode End"
 
        #region "  Private methode "
 
        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;
        }
 
        private static bool SetNodeValue(XElement node, int idx, params string[] args)
        {
            if (args.Length > idx + 1)
            {
                SetNodeValue(node.Element(args[idx]), ++idx, args);
            }
            else
            {
                node.SetValue(args[idx]);
            }
 
            return true;
        }
 
        #endregion "  Private methode End"
    }
}
 
 
cs

 

Config.xml
1
2
3
4
5
6
7
8
9
10
11
<Configuration>
 
  <DATABASE>
    <D_ADDR01>DESKTOP-OC6SJV6\BEOMBEOMJOJO</D_ADDR01>
    <D_ADDR02>DESKTOP-OC6SJV6\BEOMBEOMJOJO</D_ADDR02>
    <USER>test</USER>
    <PWD>1234</PWD>
    <SERVICE_NAME>BEOMBEOMJOJO</SERVICE_NAME>
  </DATABASE>
 
</Configuration>
cs

 

Form1.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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
using MSSQL_Connect_Program.Class;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace CSVTest
{
    public partial class Form1 : Form
    {
        public enum COLUMNS { NAME, AGE, GRADE, PHONENUMBER }
 
        List<string> csvList = null;
        List<STUDENT> stuList = new List<STUDENT>();
 
        public Form1()
        {
            InitializeComponent();
 
            //이벤트 선언
            InitEvent();
        }
 
        /// <summary>
        /// 이벤트 선언 메서드
        /// </summary>
        private void InitEvent()
        {
            //Load Event
            this.Load += FormLoad_Event;
 
            //CSV read Button Click Event
            uiBtn_ReadCsv.Click += uiBtn_ReadCsv_Click;
 
            //DataBase Insert Button Click Event
            uiBtn_DBInsert.Click += uiBtn_DBInsert_Click;
        }
 
        /// <summary>
        /// Form Load Event Handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FormLoad_Event(object sender, EventArgs e)
        {
            //MSSQL DataBase 연결
            this.Cursor = Cursors.WaitCursor;
 
            //Connect to DB
            ConnectDatabase();
 
            this.Cursor = Cursors.Default;
        }
 
        /// <summary>
        /// CSV Read Button Click Event Handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiBtn_ReadCsv_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
 
            if (fbd.ShowDialog() == DialogResult.OK)
 
            {
                string[] fileName = Directory.GetFiles(fbd.SelectedPath); //폴더 읽어와
 
                csvList = fileName.Where(x => x.IndexOf(".csv", StringComparison.OrdinalIgnoreCase) >= 0)
                               .Select(x => x).ToList();
 
                try
                {
                    GetCSVData(csvList); //CSV 파일 내용 읽어오기
                    DataSouceGridView(); //DataGridView 에 CSV 내용 바인딩
                }
                catch { }
            }
        }
 
        /// <summary>
        /// DB Insert Button Click Event Handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiBtn_DBInsert_Click(object sender, EventArgs e)
        {
            DBInsert();
        }
 
        /// <summary>
        /// CSV 파일 읽는 메서드
        /// </summary>
        /// <param name="csvList"></param>
        private void GetCSVData(List<string> csvList)
        {
            for (int idx = 0; idx < csvList.Count; idx++)
            {
                using (var sr = new System.IO.StreamReader(csvList[idx], Encoding.Default, true))
                {
                    while (!sr.EndOfStream)
                    {
                        string array = sr.ReadLine();
                        string[] values = array.Split(',');
 
                        //컬럼명은 건너뛰기
                        if (array.Contains("NAME"))
                            continue;
 
                        STUDENT stu = new STUDENT();
                        stuList.Add(SetData(stu, values));
                    }
                }
            }
        }
 
        /// <summary>
        /// Database 연결 메서드
        /// </summary>
        private void ConnectDatabase()
        {
            if (SqlDBManager.Instance.GetConnection() == false)
            {
                string msg = $"Failed to Connect to Database";
                MessageBox.Show(msg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }
 
        /// <summary>
        /// Student 객체에 데이터 저장
        /// </summary>
        /// <param name="stu"></param>
        /// <param name="values"></param>
        /// <returns></returns>
        private STUDENT SetData(STUDENT stu, string[] values)
        {
            stu.NAME = values[(int)COLUMNS.NAME].ToString();
            stu.AGE = values[(int)COLUMNS.AGE].ToString();
            stu.GRADE = values[(int)COLUMNS.GRADE].ToString();
            stu.PHONENUMBER = values[(int)COLUMNS.PHONENUMBER].ToString();
 
            return stu;
        }
 
        /// <summary>
        /// DataGridView 컨트롤에 데이터 바인딩
        /// </summary>
        private void DataSouceGridView()
        {
            // 값들이 입력된 테이블을 DataGridView에 입력합니다.
            uiGridView_CSV.DataSource = GetDataTable();
        }
 
        /// <summary>
        /// DataTable 생성
        /// </summary>
        /// <returns></returns>
        private DataTable GetDataTable()
        {
            DataTable dt = new DataTable();
 
            //컬럼 추가
            CreateColumn(dt);
 
            //Row 추가
            CreateRow(dt);
 
            return dt;
        }
 
        /// <summary>
        /// 컬럼 생성
        /// </summary>
        /// <param name="dt"></param>
        private void CreateColumn(DataTable dt)
        {
            dt.Columns.Add("Name");
            dt.Columns.Add("Age");
            dt.Columns.Add("Grade");
            dt.Columns.Add("PHONENUMBER");
        }
 
        /// <summary>
        /// Row데이터 넣기
        /// </summary>
        /// <param name="dt"></param>
        private void CreateRow(DataTable dt)
        {
            for(int idx = 0; idx < stuList.Count; idx++)
            {
                dt.Rows.Add(new string[] { stuList[idx].NAME,
                                           stuList[idx].AGE,
                                           stuList[idx].GRADE,
                                           stuList[idx].PHONENUMBER });
            }
        }
 
        /// <summary>
        /// DB Insert 메서드
        /// </summary>
        private void DBInsert()
        {
            string name = string.Empty;
            string age = string.Empty;
            string grade = string.Empty;
            string phoneNumber = string.Empty;
 
            string query = string.Empty;
 
            for (int idx = 0; idx < stuList.Count; idx++)
            {
                name = stuList[idx].NAME.ToString();
                age = stuList[idx].AGE.ToString();
                grade = stuList[idx].GRADE.ToString();
                phoneNumber = stuList[idx].PHONENUMBER.ToString();
 
                query = @"
            INSERT INTO dbo.STUDENT 
            VALUES ('#NAME', '#AGE', '#GRADE', '#PHONENUMBER')
            ";
 
                query = query.Replace("#NAME", name);
                query = query.Replace("#AGE", age);
                query = query.Replace("#GRADE", grade);
                query = query.Replace("#PHONENUMBER", phoneNumber);
 
                int result = SqlDBManager.Instance.ExecuteNonQuery(query);
 
                if (result < 0)
                {
                    MessageBox.Show("DB Insert 실패");
                }
            }
 
            MessageBox.Show("데이터베이스 Insert 성공");
        }
    }
 
    public class STUDENT
    {
        public string NAME { get; set; }
        public string AGE { get; set; }
        public string GRADE { get; set; }
        public string PHONENUMBER { get; set; }
    }
}
 
cs

 

실행 결과

 

실행 결과 “DB Insert” 버튼을 클릭하면 Database 에 알맞게 Insert 돼서 저장된 것을 확인하실 수 있습니다.

 

감사합니다.^^

728x90

이 글을 공유하기

댓글(1)

Designed by JB FACTORY