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; using ManagementSystem.Utility; namespace ExportDataToFile { public partial class Form1 : Form { //參數設定 int intExportIndex = -1; SqlConnection sqlSourceConn = new SqlConnection(); SqlConnection sqlTargetConn = new SqlConnection(); public Form1() { InitializeComponent(); } private void btnSourceConnTest_Click(object sender, EventArgs e) { try { string strCheck = CheckSource(); //查詢來源資料庫中的資料表 string strIP = txtSourceIP.Text.Trim(); string strDBName = txtSourceDBName.Text.Trim(); string strID = txtSourceID.Text.Trim(); string strPWD = txtSourcePWD.Text.Trim(); if (strCheck == "") { if (cbSourceClass.Enabled) { LockSourceForm(); switch (cbSourceClass.SelectedItem.ToString().Trim()) { case "MS-SQL": sqlSourceConn = MSSQLUtility.GetConn(strIP, strDBName, strID, strPWD); ShowMSSQLSourceTables(sqlSourceConn); Application.DoEvents(); break; case "MySQL": break; case "Oracle": break; case "PostgreSQL": break; } EnableExport(); //啟動匯出鈕 } else { UnLockSourceForm(); } } else { MessageBox.Show(strCheck); } } catch (Exception ex) { ErrorHandler.WriteErrorLog("Form1.cs", ex); } } private void btnTargetConnTest_Click(object sender, EventArgs e) { try { string strCheck = CheckTarget(); //查詢目標資料庫中的資料表 string strIP = txtTargetIP.Text.Trim(); string strDBName = txtTargetDBName.Text.Trim(); string strID = txtTargetID.Text.Trim(); string strPWD = txtTargetPWD.Text.Trim(); if (strCheck == "") { if (cbTargetClass.Enabled) { LockTargetForm(); switch (cbTargetClass.SelectedItem.ToString().Trim()) { case "MS-SQL": sqlTargetConn = MSSQLUtility.GetConn(strIP, strDBName, strID, strPWD); ShowMSSQLTargetTableList(sqlTargetConn); Application.DoEvents(); break; case "MySQL": break; case "Oracle": break; case "PostgreSQL": break; } EnableExport(); //啟動匯出鈕 } else { UnLockTargetForm(); } } else { MessageBox.Show(strCheck); } } catch (Exception ex) { ErrorHandler.WriteErrorLog("Form1.cs", ex); } } private void dgvExportList_CellEndEdit(object sender, DataGridViewCellEventArgs e) { //try //{ // dgvExportList.Rows[e.RowIndex].Cells["clExport"].Value = true; //} //catch (Exception ex) //{ // ErrorHandler.WriteErrorLog("Form1.cs", ex); //} } private void dgvExportList_CellClick(object sender, DataGridViewCellEventArgs e) { try { if (intExportIndex != e.RowIndex) { LocatedTarget(e.RowIndex); } } catch (Exception ex) { ErrorHandler.WriteErrorLog("Form1.cs", ex); } } private void dgvExportList_CellContentClick(object sender, DataGridViewCellEventArgs e) { try { var senderGrid = (DataGridView)sender; if (e.RowIndex >= 0) { //清除該列資料 if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn) { CleanExpRow(dgvExportList, e.RowIndex); } } } catch (Exception ex) { ErrorHandler.WriteErrorLog("Form1.cs", ex); } } private void cbTargetTable_SelectedIndexChanged(object sender, EventArgs e) { try { if (cbTargetTable.SelectedValue != null && intExportIndex != -1) { //重新修改DataGridView的ComboBox的內容 switch (cbTargetClass.SelectedItem.ToString().Trim()) { case "MS-SQL": ShowMSSQLTargetColumnList(sqlTargetConn, cbTargetTable.SelectedValue.ToString()); break; case "MySQL": break; case "Oracle": break; case "PostgreSQL": break; } Application.DoEvents(); } } catch (Exception ex) { ErrorHandler.WriteErrorLog("Form1.cs", ex); } } private void dgvColumnMapping_CellContentClick(object sender, DataGridViewCellEventArgs e) { try { var senderGrid = (DataGridView)sender; //觸發清除事件 if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex >= 0) { senderGrid.Rows[e.RowIndex].Cells["clExpColumn"].Value = false; ((DataGridViewComboBoxCell)senderGrid.Rows[e.RowIndex].Cells["clTargetColumn"]).Value = null; } } catch (Exception ex) { ErrorHandler.WriteErrorLog("Form1.cs", ex); } } private void dgvColumnMapping_CellEndEdit(object sender, DataGridViewCellEventArgs e) { try { if (cbTargetTable.Enabled) { //dgvColumnMapping.Rows[e.RowIndex].Cells["clExpColumn"].Value = true; //dgvExportList.Rows[intExportIndex].Cells["clExport"].Value = true; } } catch (Exception ex) { ErrorHandler.WriteErrorLog("Form1.cs", ex); } } private void btnExport_Click(object sender, EventArgs e) { try { if (cbSourceClass.SelectedIndex > 0) { string strPath = ""; sfPath.AddExtension = false; sfPath.Filter = "All files (*.*)|*.*|SQL Files(*.sql)|*.sql|txt files(*.txt)|*.txt"; sfPath.FileName = "Output" + DateTime.Now.ToString("_yyyyMMddHHmmss"); if (sfPath.ShowDialog() == DialogResult.Cancel) //如果按下取消,放棄後面動作 return; strPath = sfPath.FileName; switch (cbSourceClass.SelectedItem.ToString().Trim()) { case "MS-SQL": //匯出MS-SQL檔 ExportMSSQLData(sfPath.FileName,sfPath.DefaultExt); break; case "MySQL": break; case "Oracle": break; case "PostgreSQL": break; } } } catch (Exception ex) { ErrorHandler.WriteErrorLog("Form1.cs", ex); } } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { sqlSourceConn.Close(); sqlSourceConn = null; sqlTargetConn.Close(); sqlTargetConn = null; } private void btnMapping_Click(object sender, EventArgs e) { if (dgvColumnMapping.DataSource == null) return; //自動預設產生所有的Mapping檔案 dgvExportList.Rows[intExportIndex].Cells["clMappingData"].Value = GenMappingColumn(); dgvExportList.Rows[intExportIndex].Cells["clExport"].Value = true; //設定來源與目標的資料表對應 if (cbTargetTable.SelectedValue != null) { dgvExportList.Rows[intExportIndex].Cells["clTargetTable"].Value = cbTargetTable.SelectedValue.ToString(); } dgvExportList.Rows[intExportIndex].Cells["clWhere"].Value = txtWhere.Text.Trim(); } #region 自定義功能 #region MS-SQL public DataSet GetMSSQLResult(string strSQL) { DataSet dsData = new DataSet(); try { using (SqlDataAdapter sqlAdapter = new SqlDataAdapter(strSQL, sqlSourceConn)) { if (sqlSourceConn.State == ConnectionState.Closed) //判斷連線狀態 { sqlSourceConn.Open(); } sqlAdapter.Fill(dsData, "Result"); } return dsData; } catch (Exception ex) { throw ex; } } private void ShowMSSQLSourceTables(SqlConnection sqlConn) { try { string strGetMSSQLTableList = "Select [name] as TableName from sys.tables order by name"; dgvExportList.DataSource = MSSQLUtility.GetSQLResult(strGetMSSQLTableList, sqlConn).Tables["Result"]; } catch (Exception ex) { ErrorHandler.WriteErrorLog("Form1.cs", ex); } } private void ShowMSSQLTargetTableList(SqlConnection sqlConn) { try { string strGetMSSQLTableList = "Select [name] as TableName from sys.tables order by name"; cbTargetTable.DataSource = MSSQLUtility.GetSQLResult(strGetMSSQLTableList, sqlConn).Tables["Result"]; } catch (Exception ex) { ErrorHandler.WriteErrorLog("Form1.cs", ex); } } private void ShowMSSQLSourceColumnList(SqlConnection sqlConn, string strTableName) { try { string strGetMSSQLColumnList = "Select COLUMN_NAME,DATA_TYPE From INFORMATION_SCHEMA.COLUMNS Where TABLE_NAME ='" + strTableName + "' Order by ORDINAL_POSITION"; dgvColumnMapping.DataSource = MSSQLUtility.GetSQLResult(strGetMSSQLColumnList, sqlConn).Tables["Result"]; } catch (Exception ex) { ErrorHandler.WriteErrorLog("Form1.cs", ex); } } private void ShowMSSQLTargetColumnList(SqlConnection sqlConn, string strTableName) { try { string strGetMSSQLColumnList = "Select COLUMN_NAME From INFORMATION_SCHEMA.COLUMNS Where TABLE_NAME ='" + strTableName + "' Order by ORDINAL_POSITION"; this.clTargetColumn.DisplayMember = "COLUMN_NAME"; this.clTargetColumn.DataSource = MSSQLUtility.GetSQLResult(strGetMSSQLColumnList, sqlConn).Tables["Result"]; Application.DoEvents(); } catch (Exception ex) { ErrorHandler.WriteErrorLog("Form1.cs", ex); } } private void ExportMSSQLData(string strPath,string subFileName) { int intDataCount = 0; int intMaxData = 0; string strSourceColumns = ""; string strSourceCol = ""; string strSourceTable = ""; string strSourceType = ""; string strTargetColumns = ""; string strTargetCol = ""; string strTargetTable = ""; string strDeleteCommand = ""; string strValues = ""; string[] strColumns = null; string[,] strColumnResults = new string[dgvExportList.Rows.Count, 2]; StringBuilder sbSelectCommand = new StringBuilder(); //命令字串處理 strSourceColumns = ""; strTargetColumns = ""; //取得欄位對應字串陣列 foreach (DataGridViewRow dgvRow in dgvExportList.Rows) { if (dgvRow.Cells["clExport"].Value != null) { intDataCount = 0; intMaxData = 0; strColumns = null; sbSelectCommand.Clear(); strSourceTable = ""; strSourceColumns = ""; strSourceType = ""; strTargetTable = ""; strTargetColumns = ""; strDeleteCommand = ""; strValues = ""; DataTable dtResult = null; //取得欄位對應 if (dgvRow.Cells["clMappingData"].Value != null) { strColumns = dgvRow.Cells["clMappingData"].Value.ToString().Split('|'); } //取得欄位上限 if (dgvRow.Cells["clMaxRecord"].Value != null) { intMaxData = Int32.Parse(dgvRow.Cells["clMaxRecord"].Value.ToString()); } #region 產生來源資料查詢命令 foreach (string RowData in strColumns) { strSourceCol = RowData.Substring(0, RowData.IndexOf(',')).Trim(); strSourceType = RowData.Substring(RowData.IndexOf(',') + 1, RowData.IndexOf(';') - 1 - RowData.IndexOf(',')).Trim(); strTargetCol = RowData.Substring(RowData.IndexOf(';') + 1).Trim(); if (strTargetCol == "") { strTargetCol = strSourceCol; } if (strSourceColumns == "") { strSourceColumns += ConvertMSSQLColumnType(strSourceCol, strTargetCol, strSourceType); strTargetColumns += "[" + strTargetCol + "]"; } else { strSourceColumns += "," + ConvertMSSQLColumnType(strSourceCol, strTargetCol, strSourceType); strTargetColumns += ",[" + strTargetCol + "]"; } } if (dgvRow.Cells["clSourceTable"].Value != null) { strSourceTable = dgvRow.Cells["clSourceTable"].Value.ToString(); sbSelectCommand.AppendLine(string.Format("Select {0} From {1} ", strSourceColumns, strSourceTable)); } if (dgvRow.Cells["clWhere"].Value != null) { if (dgvRow.Cells["clWhere"].Value.ToString().Trim() != "") { sbSelectCommand.AppendLine("Where 1=1 And " + dgvRow.Cells["clWhere"].Value.ToString()); } } #endregion #region 產生匯出資料語法 dtResult = GetMSSQLResult(sbSelectCommand.ToString()).Tables["Result"]; if (dtResult.Rows.Count > 0) { if (dgvRow.Cells["clTargetTable"].Value != null) { strTargetTable = dgvRow.Cells["clTargetTable"].Value.ToString(); Utility.WriteFile(strPath + ".sql", " "); Utility.WriteFile(strPath + ".sql", string.Format("/*======================================================={0}======================================================*/", strTargetTable)); Utility.WriteFile(strPath + ".sql", string.Format("raiserror('Now Insert {0} Datas .... ', 1, 1)", strTargetTable)); Utility.WriteFile(strPath + ".sql", "Go"); } //勾選清除目標資料表 if (dgvRow.Cells["clTableDel"].Value != null) { strDeleteCommand = string.Format("Delete From {0} ", strTargetTable); if (dgvRow.Cells["clWhere"].Value != null) { if (dgvRow.Cells["clWhere"].Value.ToString().Trim() != "") { strDeleteCommand += "Where 1=1 And " + dgvRow.Cells["clWhere"].Value.ToString(); } } Utility.WriteFile(strPath + ".sql", strDeleteCommand + ";"); Utility.WriteFile(strPath + ".sql", "Go"); } //處理筆數上限似資料匯出 string strFileCount = ""; foreach (DataRow dr in dtResult.Rows) { strFileCount = (intDataCount / intMaxData).ToString(); //切分檔案 foreach (DataColumn dc in dtResult.Columns) { if (strValues == "") { strValues = ConvertMSSQLDataType(dr[dc].ToString().Trim(), dc.DataType.ToString()); } else { strValues += "," + ConvertMSSQLDataType(dr[dc].ToString().Trim(), dc.DataType.ToString()); } } if (intMaxData == 0) { //無設定最大筆數 Utility.WriteFile(strPath + ".sql", string.Format("Insert Into {0} ({1}) Values ({2}) ", strTargetTable, strTargetColumns, strValues)); } else { //有設定最大筆數 if (strFileCount == "0") strFileCount = ""; Utility.WriteFile(strPath + strFileCount + ".sql", string.Format("Insert Into {0} ({1}) Values ({2}) ", strTargetTable, strTargetColumns, strValues)); } intDataCount += 1; strValues = ""; //清除已經存在的資料 } Utility.WriteFile(strPath + strFileCount + ".sql", "Go"); } } #endregion } MessageBox.Show("匯出完成"); } #endregion //End of MS-SQL private string CheckSource() { try { string strResult = ""; if (cbSourceClass.SelectedIndex <= 0) { strResult = "請選擇來源資料庫類別"; cbSourceClass.Focus(); return strResult; } else { if (txtSourceIP.Text.Trim() == "") { strResult = "來源資料庫IP為必填"; txtSourceIP.Focus(); return strResult; } if (txtSourceDBName.Text.Trim() == "") { strResult = "來源資料庫名稱為必填"; txtSourceDBName.Focus(); return strResult; } if (txtSourceID.Text.Trim() == "") { strResult = "來源資料庫帳號為必填"; txtSourceID.Focus(); return strResult; } } return strResult; } catch (Exception ex) { ErrorHandler.WriteErrorLog("Form1.cs", ex); return "發生不明錯誤!"; } } private string CheckTarget() { try { string strResult = ""; if (cbTargetClass.SelectedIndex <= 0) { strResult = "請選擇目標資料庫類別"; cbTargetClass.Focus(); return strResult; } else { if (txtTargetIP.Text.Trim() == "") { strResult = "目標資料庫IP為必填"; txtTargetIP.Focus(); return strResult; } if (txtTargetDBName.Text.Trim() == "") { strResult = "目標資料庫名稱為必填"; txtTargetDBName.Focus(); return strResult; } if (txtTargetID.Text.Trim() == "") { strResult = "目標資料庫帳號為必填"; txtTargetID.Focus(); return strResult; } } return strResult; } catch (Exception ex) { ErrorHandler.WriteErrorLog("Form1.cs", ex); return "發生不明錯誤!"; } } private void LockSourceForm() { try { cbSourceClass.Enabled = false; txtSourceIP.Enabled = false; txtSourceID.Enabled = false; txtSourceDBName.Enabled = false; txtSourcePWD.Enabled = false; btnSourceConnTest.Text = "連線中…"; } catch (Exception ex) { ErrorHandler.WriteErrorLog("Form1.cs", ex); } } private void UnLockSourceForm() { try { cbSourceClass.Enabled = true; txtSourceIP.Enabled = true; txtSourceID.Enabled = true; txtSourceDBName.Enabled = true; txtSourcePWD.Enabled = true; btnSourceConnTest.Text = "建立來源連線"; } catch (Exception ex) { ErrorHandler.WriteErrorLog("Form1.cs", ex); } } private void LockTargetForm() { try { cbTargetClass.Enabled = false; cbTargetTable.Enabled = true; cbTargetTable.SelectedIndex = -1; txtTargetIP.Enabled = false; txtTargetID.Enabled = false; txtTargetDBName.Enabled = false; txtTargetPWD.Enabled = false; btnTargetConnTest.Text = "連線中…"; } catch (Exception ex) { ErrorHandler.WriteErrorLog("Form1.cs", ex); } } private void UnLockTargetForm() { try { cbTargetClass.Enabled = true; cbTargetTable.DataSource = null; cbTargetTable.Enabled = false; txtTargetIP.Enabled = true; txtTargetID.Enabled = true; txtTargetDBName.Enabled = true; txtTargetPWD.Enabled = true; btnTargetConnTest.Text = "建立目標連線"; } catch (Exception ex) { ErrorHandler.WriteErrorLog("Form1.cs", ex); } } private string GenMappingColumn() { string strExportColumns = ""; string strSourceColumn = ""; string strTargetColumn = ""; string strSourceColType = ""; //預設所有欄位均匯出 foreach (DataGridViewRow dgRow in dgvColumnMapping.Rows) { //處理下拉欄位空白的問題 if (dgRow.Cells["clExpColumn"].Value != null) { if ((bool)dgRow.Cells["clExpColumn"].Value == true) { if (dgRow.Cells["clSourceColumn"].Value == null) { strSourceColumn = " "; } else { strSourceColumn = dgRow.Cells["clSourceColumn"].Value.ToString(); } if (dgRow.Cells["clType"].Value == null) { strSourceColType = " "; } else { strSourceColType = dgRow.Cells["clType"].Value.ToString(); } if (dgRow.Cells["clTargetColumn"].Value == null) { strTargetColumn = " "; } else { strTargetColumn = dgRow.Cells["clTargetColumn"].Value.ToString(); } if (strExportColumns == "") { strExportColumns += strSourceColumn + "," + strSourceColType + ";" + strTargetColumn; } else { strExportColumns += "|" + strSourceColumn + "," + strSourceColType + ";" + strTargetColumn; } } } } return strExportColumns; } private void LocatedTarget(int intRowIndex) { if (cbTargetClass.SelectedIndex >= 0 && cbTargetClass.Enabled == false) { //cbTargetTable.SelectedValue = dgvExportList.Rows[intRowIndex].Cells["clSourceTable"].Value.ToString(); string strTarget = ""; string[] strColumnMapping = null; if (intRowIndex != -1) { intExportIndex = intRowIndex; //設定目標Table下拉式選單的內容 if (dgvExportList.Rows[intRowIndex].Cells["clTargetTable"].Value != null && dgvExportList.Rows[intRowIndex].Cells["clTargetTable"].Value.ToString() != "") { strTarget = dgvExportList.Rows[intRowIndex].Cells["clTargetTable"].Value.ToString(); } else { strTarget = dgvExportList.Rows[intRowIndex].Cells["clSourceTable"].Value.ToString(); } cbTargetTable.SelectedValue = strTarget; //取得欄位對應字串陣列 if (dgvExportList.Rows[intRowIndex].Cells["clMappingData"].Value != null) { strColumnMapping = dgvExportList.Rows[intRowIndex].Cells["clMappingData"].Value.ToString().Split('|'); } //顯示欄位對應表的內容 if (cbTargetTable.SelectedValue != null) { switch (cbTargetClass.SelectedItem.ToString().Trim()) { case "MS-SQL": ShowMSSQLSourceColumnList(sqlSourceConn, strTarget.ToString()); Application.DoEvents(); break; case "MySQL": break; case "Oracle": break; case "PostgreSQL": break; } } if (strColumnMapping != null) { string strSourceColumn = ""; string strTargetColumn = ""; foreach (string strColumn in strColumnMapping) { strSourceColumn = strColumn.Substring(0, strColumn.IndexOf(',')).Trim(); strTargetColumn = strColumn.Substring(strColumn.IndexOf(',') + 1).Trim(); foreach (DataGridViewRow dgvRow in dgvColumnMapping.Rows) { if (dgvRow.Cells["clSourceColumn"].Value.ToString() == strSourceColumn) { dgvRow.Cells[0].Value = true; } } } } else { //預設所有欄位均匯出 foreach (DataGridViewRow dgRow in dgvColumnMapping.Rows) { ((DataGridViewCheckBoxCell)dgRow.Cells["clExpColumn"]).Value = true; } } //設定Where條件 if (dgvExportList.Rows[intRowIndex].Cells["clWhere"].Value != null) { txtWhere.Text = dgvExportList.Rows[intRowIndex].Cells["clWhere"].Value.ToString(); } else { txtWhere.Text = ""; } } } } private void CleanExpRow(DataGridView senderGrid, int intRowIndex) { senderGrid.Rows[intRowIndex].Cells["clExport"].Value = false; senderGrid.Rows[intRowIndex].Cells["clTargetTable"].Value = ""; senderGrid.Rows[intRowIndex].Cells["clTableDel"].Value = false; senderGrid.Rows[intRowIndex].Cells["clMaxRecord"].Value = ""; senderGrid.Rows[intRowIndex].Cells["clWhere"].Value = ""; senderGrid.Rows[intRowIndex].Cells["clMappingData"].Value = ""; CleanMappingRow(senderGrid, intRowIndex); txtWhere.Text = ""; Application.DoEvents(); } private void CleanMappingRow(DataGridView senderGrid,int intRowIndex) { DataTable CleanTable = (DataTable)dgvColumnMapping.DataSource; CleanTable.Rows.Clear(); dgvColumnMapping.DataSource = CleanTable; } private void EnableExport() { if (sqlSourceConn.State.ToString().ToUpper() == "OPEN" && sqlTargetConn.State.ToString().ToUpper() == "OPEN") { btnExport.Enabled = true; } } private string ConvertMSSQLColumnType(string strSourceCol, string strTargetCol, string strType) { switch (strType.ToUpper()) { case "VARCHAR": return "[" + strSourceCol + "] AS " + strTargetCol ; case "VAR": return "[" + strSourceCol + "] AS " + strTargetCol ; case "INT": return "[" + strSourceCol + "] AS " + strTargetCol; case "DATETIME": return "Convert(varchar,[" + strSourceCol + "],21) AS " + strTargetCol; default: return "[" + strSourceCol + "] AS " + strTargetCol; } } private string ConvertMSSQLDataType(string strData, string strType) { if(strData == "") { return "Null"; } switch (strType.ToUpper()) { case "STRING": return "'" + strData.ToString().Trim() + "'"; case "INT32": return strData.ToString().Trim(); case "DECIMAL": return strData.ToString().Trim(); default: return "'" + strData.ToString().Trim() + "'"; } } #endregion } }