IT/C#
CSV파일 자료를 DataGrid에 옮긴 후(확인) 데이터베이스에 등록하기
chubbyBear
2020. 10. 15. 15:20
CSV파일 자료를 DB에 등록하고자 하는 자료 중 일부 항목(코드번호 등)을 자동으로 생성할 필요가 있을 경우, CSV파일 자료 구조를 DB Table 구조에 동일하게 맞출 수 없게되므로, 쿼리로 한번에 DB에 등록할 수 없게된다.
그래서, C#의 파일스트림(StreamReader)를 사용해서 CSV파일의 데이터를 하나씩 읽어 들이면서, DataGrid에 전부 넣은 후, Insert로 한번에 DB에 자료를 등록하는 방법 사용했다.
여기서, 자동생성 항목은 CSV파일 자료를 읽어들인 후 자동생성해서 DaataGrid에 넣는다.
즉, DataGrid를 DB Table 구조에 맞추어 주면 끝.
이하 코드 참조.
파일스트림으로 CSV파일의 자료는 읽어오는 방법은 이하 코드의 "CSVFileRead()" 함수 참조.
public partial class BookManageStatsViewDB : UserControl
{
private DatabaseControl dbcontrol;
private static List<FeildDataClassBookInsert> rowItem;
private static ArrayList codeNumbers;
private const string _tableName = "booklisttable";
private const string _bookcode = "Book_code";
private const string _bookname = "Book_name";
private const string _authorname = "Author_name";
private const string _publisher = "Publisher";
private const string _grouping = "Group_section";
private const string _purchasedate = "Purchase_date";
private const string _donationdate = "Donation_date";
private const string _donor = "Donor";
private const string _price = "Price";
private const string _qty = "Qty";
//private const string _status = "Status";
private const string _note = "Note";
public BookManageStatsViewDB()
{
InitializeComponent();
rowItem = new List<FeildDataClassBookInsert>();
codeNumbers = new ArrayList();
}
private void StartBtn_Click(object sender, RoutedEventArgs e)
{
CSVFileRead();
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
DataaseField fields;
CommonPage com = new CommonPage();
fields = com.DBKeySetting();
if (fields == null)
{
MessageBox.Show("데이터베이스 연결 정보가 올바르지 않습니다.");
// Control 전체 비활성화
MainGrid.IsEnabled = false;
return;
}
dbcontrol = new DatabaseControl(fields.PortNumber, fields.ServerAddress, fields.DatabaseName, fields.ID, fields.Password);
if (dbcontrol == null)
{
MessageBox.Show("데이터베이스 초기화에 실패했습니다.");
// Control 전체 비활성화
MainGrid.IsEnabled = false;
return;
}
}
private void CSVFileRead()
{
StreamReader readfilw = new StreamReader(@"D:\book_list_updateforuse.csv");
while(!readfilw.EndOfStream)
{
string rowLine = readfilw.ReadLine();
string[] colData = rowLine.Split(',');
FeildAddDataViewGd.ItemsSource = null;
string bookCodeStr = BookCodeCalValue(colData[3]);
// List에 각각의 TextBox.Text값을 저장
rowItem.Add(new FeildDataClassBookInsert()
{
Book_code = bookCodeStr,
Book_name = colData[0],
Author_name = colData[1],
Publisher = colData[2],
Grouping = colData[3],
Purchase_date = colData[4],
Donation_date = colData[5],
Donor = colData[6],
Price = colData[7],
Qty = "1",
Note = "",
}); ;
codeNumbers.Add(bookCodeStr);
FeildAddDataViewGd.ItemsSource = rowItem;
FeildAddDataViewGd.Items.Refresh();
}
}
private string BookCodeCalValue(string groupNameStr)
{
string codeStr = "";
//"SELECT Count(*) FROM " + tableName + "
string query = "select Count(*) from ";
query += _tableName;
query += " where ";
query += _tableName + "." + _grouping;
query += "=";
query += "'";
query += groupNameStr;
query += "'";
string queryCodeTable = "select Code_ID from codetable";
queryCodeTable += " where Item_name=";
queryCodeTable += "'";
queryCodeTable += groupNameStr;
queryCodeTable += "'";
if (dbcontrol == null)
{
return "";
}
int count = dbcontrol.Count(query);
DataTable data = dbcontrol.Select(queryCodeTable);
DataView view = data.DefaultView;
// count값을 정상적으로 취득했다면
if (count > -1)
{
count += 1;
count += (int)view[0].Row[0];
// 버퍼크기만큼 배열에 저장값중 현재 취득한 값과 동일한 값이 있으면 +1
if (codeNumbers.Count > 0)
{
for (int cnt = 0; cnt < codeNumbers.Count; cnt++)
{
if (count == int.Parse(codeNumbers[cnt].ToString()))
{
count += 1;
}
}
}
codeStr = count.ToString();
}
return codeStr;
}
private void insertBtn_Click(object sender, RoutedEventArgs e)
{
string queryStr;
queryStr = "insert into " + _tableName + "(" + _bookcode + "," + _bookname + "," + _authorname + "," + _publisher + ","
+ _grouping + "," + _purchasedate + "," + _donationdate + "," + _donor + ","
+ _price + "," + _qty + "," + _note + ")" + " values";
List<FeildDataClassBookInsert> temp = FeildAddDataViewGd.ItemsSource as List<FeildDataClassBookInsert>;
if (temp != null)
{
if (temp.Count != 0)
{
if (MessageBox.Show("데이터 " + temp.Count.ToString() + "건이 존재합니다.\n데이터베이스에 등록합니까?", "등록", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.OK)
{
for (int i = 0; i < temp.Count; i++)
{
queryStr += "(" + temp[i].Book_code + ","
+ "'" + temp[i].Book_name + "'" + ","
+ "'" + temp[i].Author_name + "'" + ","
+ "'" + temp[i].Publisher + "'" + ","
+ "'" + temp[i].Grouping + "'" + ","
+ "'" + temp[i].Purchase_date + "'" + ","
+ "'" + temp[i].Donation_date + "'" + ","
+ "'" + temp[i].Donor + "'" + ","
+ "'" + temp[i].Price + "'" + ","
+ temp[i].Qty + ","
+ "'" + temp[i].Note + "'" + ")";
if (i < (temp.Count - 1))
{
queryStr += ",";
}
}
string result = dbcontrol.Insert(queryStr);
if (String.IsNullOrEmpty(result))
{
temp.Clear();
FeildAddDataViewGd.ItemsSource = temp;
FeildAddDataViewGd.Items.Refresh();
}
else if (result == "1062")
{
MessageBox.Show("입력된 정보는 이미 데이터베이스에 존재합니다.\n입력정보를 수정해 주세요.");
}
else
{
MessageBox.Show("데이터베이스의 INSERT 규약위반 입니다.\n또는 입력한 정보에 문제가 있을 수 있습니다.\n다시 한번 확인해 주십시오.");
}
}
}
else
{
MessageBox.Show("데이터베이스에 등록할 대상이 있는지 다시한번 확인해 주세요.");
}
}
else
{
MessageBox.Show("데이터베이스에 등록할 자료가 없습니다.");
}
}
}