using AR;
using MySql.Data.MySqlClient;
using Renci.SshNet;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using UniMarc.BaroService_TI;
using UniMarc.Properties;

namespace UniMarc
{
    /// <summary>
    /// DB접속을 도와주는 클래스
    /// </summary>
    public partial class Helper_DB
    {
        // 접속
        MySqlConnection conn;

        /// <summary>
        /// IP / Port / Uid / pwd
        /// </summary>
        static string[] ServerData = {
            Settings.Default.IP,
            Settings.Default.Uid,
            Settings.Default.pwd
        };
        int port = Settings.Default.Port;

        static string[] DBData = {
            Settings.Default.dbPort,
            Settings.Default.dbUid,
            Settings.Default.dbPwd
        };

        // 쿼리
        MySqlCommand sqlcmd = new MySqlCommand();
        MySqlDataReader sd;

        public MySqlConnection CreateConnection()
        {
            PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo(ServerData[0], port, ServerData[1], ServerData[2]);
            connectionInfo.Timeout = TimeSpan.FromSeconds(30);
            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();
                if (client.IsConnected)
                {
                    string strConnection = string.Format(
                        "Server={0};" +
                        "Port={1};" +
                        "Database=unimarc;" +
                        "uid={2};" +
                        "pwd={3};", ServerData[0], DBData[0], DBData[1], DBData[2]);
                    return new MySqlConnection(strConnection);
                }
            }

            return null;
        }


        /// <summary>
        /// DB를 사용하고 싶을 때 미리 저장된 DB의 기본 접속정보를 이용하여 DB에 접근한다.
        /// </summary>
        public void DBcon()     // DB접속 함수
        {
            //"Server=1.215.250.130;Port=3306;Database=unimarc;uid=root;pwd=Admin21234;"
            PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo(ServerData[0], port, ServerData[1], ServerData[2]);
            connectionInfo.Timeout = TimeSpan.FromSeconds(30);
            using (var client = new SshClient(connectionInfo))
            {
                if (conn != null)
                {
                    conn.Close();
                    conn.Dispose();
                }
                client.Connect();
                if (client.IsConnected)
                {
                    var cs = string.Format(
                        "Server={0};" +
                        "Port={1};" +
                        "Database=unimarc;" +
                        "uid={2};" +
                        "pwd={3};", ServerData[0], DBData[0], DBData[1], DBData[2]);
                    conn = new MySqlConnection(cs);
                }
            }
        }


        /// <summary>
        /// 국중DB를 사용하고 싶을 때 미리 저장된 DB의 기본 접속정보를 이용하여 DB에 접근한다.
        /// </summary>
        public void DBcon_cl()     // DB접속 함수 
        {
            PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo(ServerData[0], port, ServerData[1], ServerData[2]);
            connectionInfo.Timeout = TimeSpan.FromSeconds(30);
            using (var client = new SshClient(connectionInfo))
            {
                if (conn != null)
                {
                    conn.Close();
                    conn.Dispose();
                }
                client.Connect();
                if (client.IsConnected)
                {
                    string strConnection = string.Format(
                        "Server={0};" +
                        "Port={1};" +
                        "Database=cl_marc;" +
                        "uid={2};" +
                        "pwd={3};", ServerData[0], DBData[0], DBData[1], DBData[2]);
                    conn = new MySqlConnection(strConnection);
                }
            }
        }


        public string DB_Send_CMD_Search(string cmd)
        {

            // DB 연결
            conn.Open();
            // 쿼리 맵핑
            sqlcmd.CommandText = cmd;
            // 쿼리 날릴 곳은 conn
            sqlcmd.Connection = conn;
            // 쿼리 날리기, sqlDataReader에 결과값 저장
            sd = sqlcmd.ExecuteReader();
            string result = "";
            string change;
            // 한줄씩 불러와 한개의 값으로 변환
            while (sd.Read())
            {
                for (int count = 0; count < sd.FieldCount; count++)
                {
                    change = sd[count].ToString().Replace("|", "");
                    result += change + "|";
                }
            }
            conn.Close();
            return result;
        }

        public DataTable DB_Send_CMD_Search_DataTable(string cmd)
        {
            DataTable dt = new DataTable();
            try
            {
                if (conn.State == ConnectionState.Closed)
                    conn.Open();

                using (MySqlDataAdapter adapter = new MySqlDataAdapter(cmd, conn))
                {
                    adapter.Fill(dt);
                }
            }
            catch (Exception ex)
            {
                UTIL.MsgE($"데이터베이스 실행오류\n{ex.Message}");
                return null;
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                    conn.Close();
            }
            return dt;
        }
        public void DB_Send_CMD_Search_ApplyGrid(string cmd, DataGridView dgv)
        {
            // DB 연결
            conn.Open();
            // 쿼리 맵핑
            sqlcmd.CommandText = cmd;
            // 쿼리 날릴 곳은 conn
            sqlcmd.Connection = conn;
            // 쿼리 날리기, sqlDataReader에 결과값 저장
            sd = sqlcmd.ExecuteReader();

            int colCount = dgv.ColumnCount;
            string[] grid = new string[colCount];
            int AddCol = 0;

            // 한줄씩 불러와 한개의 값으로 변환
            while (sd.Read())
            {
                for (int count = 0; count < sd.FieldCount; count++)
                {
                    string change = sd[count].ToString().Replace("|", "");
                    grid[AddCol] = change;

                    if (colCount - 1 == AddCol)
                    {
                        AddCol = 0;
                        dgv.Rows.Add(grid);
                    }
                    else
                    {
                        AddCol++;
                    }
                }
            }
            conn.Close();
        }

        public void DB_Send_CMD_Search_GetGridData(string cmd, DataGridView pDgv)
        {
            // DB 연결
            conn.Open();
            // 쿼리 맵핑
            sqlcmd.CommandText = cmd;
            // 쿼리 날릴 곳은 conn
            sqlcmd.Connection = conn;
            // 쿼리 날리기, sqlDataReader에 결과값 저장
            sd = sqlcmd.ExecuteReader();
            MySqlDataReader tReturnSd = sd;
            int colCount = pDgv.ColumnCount - 1;
            string[] grid = new string[pDgv.ColumnCount];
            int AddCol = 0;

            // 한줄씩 불러와 한개의 값으로 변환
            while (sd.Read())
            {
                for (int count = 0; count < sd.FieldCount; count++)
                {
                    string change = sd[count].ToString().Replace("|", "");
                    grid[AddCol] = change;
                    if (colCount - 1 == AddCol)
                    {
                        AddCol = 0;
                        grid[colCount] = "추가";
                        pDgv.Rows.Add(grid);
                    }
                    else
                    {
                        AddCol++;
                    }
                }
            }
            conn.Close();
        }


        /// <summary>
        /// DBcon이 선진행되어야함.
        /// SELECT * FROM [DB_Table_Name] WHERE [DB_Where_Table] LIKE \"%DB_Search_Data%\"
        /// <summary>
        /// <param name="compidx"/>이용자 회사의 idx번호 단.none일 경우 다른 DB를 가져옴</param>
        /// <param name="DB_Table_Name">테이블명</param>
        /// <param name="DB_Where_Table">검색할 테이블</param>
        /// <param name="DB_Search_Data">검색할 텍스트</param>
        /// <returns>검색된 결과값이 반환됨.</returns>
        public string DB_Contains(string DB_Table_Name, string compidx,
                                  string DB_Where_Table = "", string DB_Search_Data = "",
                                  string Search_col = "",
                                  string DB_Where_Table1 = "", string DB_Search_Data1 = "")
        {
            string cmd = "SELECT ";
            if (Search_col == "") { cmd += "*"; }
            else { cmd += Search_col; }
            cmd += " FROM ";
            cmd += DB_Table_Name;
            if (DB_Table_Name == "Obj_List") { cmd += " WHERE `comp_num` = \"" + compidx + "\""; }
            else if (DB_Table_Name == "Client") { cmd += " WHERE `campanyidx` = \"" + compidx + "\""; }
            else if (DB_Table_Name == "Purchase") { cmd += " WHERE `comparyidx` = \"" + compidx + "\""; }
            else if (compidx == "none") { cmd += " WHERE `grade` = \"2\""; }
            else { cmd += " WHERE `compidx` = \"" + compidx + "\""; }

            if (DB_Search_Data != "")
            {
                cmd += " AND `" + DB_Where_Table + "` LIKE \"%" + DB_Search_Data + "%\"";
            }
            if (DB_Search_Data1 != "")
            {
                cmd += " AND `" + DB_Where_Table1 + "` LIKE \"%" + DB_Search_Data1 + "%\"";
            }
            cmd += ";";
            return cmd;
        }
        /// <summary>
        /// DBcon이 선진행되어야함. / SELECT * FROM DB_Table_Name WHERE DB_Where_Table = \"DB_Search_Data\";
        /// <summary>
        /// <param name="Search_Area">가져올 데이터의 위치</param>
        /// <param name="DB_Table_Name">테이블명</param>
        /// <param name="DB_Where_Table">검색할 테이블</param>
        /// <param name="DB_Search_Data">검색할 텍스트</param>
        /// <returns>검색된 결과값이 반환됨.</returns>
        public string DB_Select_Search(string Search_Area, string DB_Table_Name,
            string DB_Where_Table = "", string DB_Search_Data = "",
            string DB_Where_Table1 = "", string DB_Search_Data1 = "")
        {
            string cmd = string.Format("SELECT {0} FROM ", Search_Area);
            cmd += DB_Table_Name;
            if (DB_Where_Table != "" && DB_Search_Data != "")
            {
                cmd += string.Format(" WHERE `{0}` = \"{1}\"", DB_Where_Table, DB_Search_Data);
            }
            if (DB_Where_Table1 != "" && DB_Search_Data1 != "")
            {
                cmd += string.Format(" AND `{0}` = \"{1}\"", DB_Where_Table1, DB_Search_Data1);
            }
            cmd += ";";
            return cmd;
        }
        /// <summary>
        /// DBcon이 선진행되어야함. / SELECT * FROM DB_Table_Name WHERE DB_Where_Table = \"DB_Search_Data\";
        /// <summary>
        /// <param name="DB_Table_Name">테이블명</param>
        /// <param name="DB_Where_Table">검색할 테이블</param>
        /// <param name="DB_Search_Data">검색할 텍스트</param>
        /// <returns>검색된 결과값이 반환됨.</returns>
        public string DB_Search(string DB_Table_Name,
            string DB_Where_Table = "", string DB_Search_Data = "",
            string DB_Where_Table1 = "", string DB_Search_Data1 = "")
        {
            string cmd = "SELECT * FROM ";
            cmd += DB_Table_Name;// + " where id=\"id\"";
            if (DB_Search_Data != "")
            {
                cmd += " WHERE " + DB_Where_Table + "=\"" + DB_Search_Data + "\"";
            }
            if (DB_Where_Table1 != "" && DB_Search_Data1 != "")
            {
                cmd += " AND `" + DB_Where_Table1 + "` =\"" + DB_Search_Data1 + "\"";
            }
            cmd += ";";
            return cmd;
        }
        /// <summary>
        /// 여러 조건이 있을때 사용 (단, Where_Table과 Search_Date의 배열길이는 같아야함)
        /// </summary>
        /// <param name="DB_Table_Name"></param>
        /// <param name="DB_Where_Table"></param>
        /// <param name="DB_Search_Data"></param>
        /// <param name="Search_Table">추출할 열의 이름."`num1`, `num2`" 이런식으로</param>
        /// <returns></returns>
        public string More_DB_Search(String DB_Table_Name, String[] DB_Where_Table,
            String[] DB_Search_Data, String Search_Table = "")
        {
            if (DB_Where_Table.Length != DB_Search_Data.Length) { return "오류발생"; }
            string cmd = "SELECT ";
            if (Search_Table == "") { cmd += "*"; }
            else { cmd += Search_Table; }
            cmd += " FROM " + DB_Table_Name + " WHERE ";
            for (int a = 0; a < DB_Where_Table.Length; a++)
            {
                cmd += "`" + DB_Where_Table[a] + "` = \"" + DB_Search_Data[a] + "\" ";
                if (a == DB_Where_Table.Length - 1) { cmd += ";"; }
                else { cmd += " AND "; }
            }
            return cmd;
        }
        /// <summary>
        /// DB상의 날짜의 사이값을 가져오기 위한 함수
        /// </summary>
        /// <param name="Table_name">가져올 테이블의 이름</param>
        /// <param name="Search_Table">프로그램상으로 가져올 DB데이터</param>
        /// <param name="Search_date">DB상의 날짜가 저장된 컬럼명</param>
        /// <param name="start_date">시작할 날짜 0000-00-00</param>
        /// <param name="end_date">끝낼 날짜 0000-00-00</param>
        /// <param name="compidx">회사 인덱스 main.com_idx</param>
        /// <returns></returns>
        public string Search_Date(string Table_name, string Search_Table, string Search_date,
            string start_date, string end_date, string compidx)
        {
            if (Search_Table == "") { Search_Table = "*"; }
            // select * from `table_name` where `날짜 컬럼` between date('start_date') and date('end_date')+1;
            string cmd = "SELECT " + Search_Table + " FROM `" + Table_name + "` " +
                "WHERE `comp_num` = '" + compidx + "' AND `" +
                Search_date + "` >= '" + start_date + "'";
            if (Table_name != "Obj_List") { cmd = cmd.Replace("`comp_num`", "`compidx`"); }
            if (end_date != "") { cmd += " AND `" + Search_date + "` <= '" + end_date + "';"; }
            else { cmd += ";"; }
            return cmd;
        }
        public string DB_INSERT(String DB_Table_name, String[] DB_col_name, String[] setData)
        {
            string cmd = "INSERT INTO " + DB_Table_name + "(";
            for (int a = 0; a < DB_col_name.Length; a++)
            {
                if (a == DB_col_name.Length - 1) { cmd += "`" + DB_col_name[a] + "`) "; }
                else { cmd += "`" + DB_col_name[a] + "`, "; }
            }
            cmd += "values(";
            for (int a = 0; a < setData.Length; a++)
            {
                setData[a] = setData[a].Replace("\"", "\"\"");
                if (a == setData.Length - 1) { cmd += "\"" + setData[a] + "\")"; }
                else { cmd += "\"" + setData[a] + "\", "; }
            }
            cmd += ";";
            cmd = cmd.Replace("|", "");
            return cmd;
        }
        public string DB_INSERT_SUB(string value, string[] setData)
        {
            string cmd = string.Format("(");
            if (value == "")
            {
                for (int a = 0; a < setData.Length; a++)
                {
                    if (a == setData.Length - 1) { cmd += "`" + setData[a] + "`) "; }
                    else { cmd += "`" + setData[a] + "`, "; }
                }
                return cmd;
            }
            for (int a = 0; a < setData.Length; a++)
            {
                setData[a] = setData[a].Replace("\"", "\"\"");
                if (a == setData.Length - 1) { cmd += "\"" + setData[a] + "\")"; }
                else { cmd += "\"" + setData[a] + "\", "; }
            }
            return cmd;
        }
        /// <summary>
        /// 대상 컬럼 삭제   / DELETE FROM "DB_Table_Name" WHERE "target_idx"="comp_idx" AND "target_area"="target";
        /// </summary>
        /// <param name="DB_Table_Name">삭제할 대상이 있는 테이블명</param>
        /// <param name="target_idx">인덱스 대상이 있는 열명</param>
        /// <param name="comp_idx">삭제할 대상의 인덱스</param>
        /// <param name="target_area">삭제할 대상이 있는 열명</param>
        /// <param name="target">삭제할 대상</param>
        public string DB_Delete(string DB_Table_Name,
            string target_idx, string comp_idx,
            string target_area, string target)
        {
            string cmd = "DELETE FROM " + DB_Table_Name + " WHERE " +
                "`" + target_idx + "`=\"" + comp_idx + "\" AND" +
                "`" + target_area + "`=\"" + target + "\" LIMIT 1;";
            return cmd;
        }
        /// <summary>
        /// 대상 컬럼 삭제(리미트 없음) / DELETE FROM "DB_Table_Name" WHERE "target_idx"="comp_idx" AND "target_area"="target";
        /// </summary>
        /// <param name="DB_Table">대상 테이블명</param>
        /// <param name="target_idx">회사 인덱스 컬럼명</param>
        /// <param name="comp_idx">회사 인덱스</param>
        /// <param name="target_area">삭제 대상의 컬럼명</param>
        /// <param name="target">삭제 대상</param>
        public string DB_Delete_No_Limit(string DB_Table,
            string target_idx, string comp_idx,
            string[] target_area, string[] target)
        {
            string cmd = string.Format("DELETE FROM {0} WHERE `{1}`= \"{2}\" AND", DB_Table, target_idx, comp_idx);
            for (int a = 0; a < target_area.Length; a++)
            {
                cmd += string.Format("`{0}`=\"{1}\"", target_area[a], target[a]);
                if (a != target_area.Length - 1) { cmd += " AND"; }
            }
            cmd += ";";
            return cmd;
        }
        /// <summary>
        /// 대상 컬럼 삭제   / DELETE FROM "DB_Table_Name" WHERE "target_idx"="comp_idx" AND "target_area"="target";
        /// </summary>
        public string DB_Delete_More_term(string DB_Table_Name,
            string target_idx, string comp_idx,
            string[] target_area, string[] target)
        {
            string cmd = "DELETE FROM " + DB_Table_Name + " WHERE " +
                "`" + target_idx + "`=\"" + comp_idx + "\" AND";
            for (int a = 0; a < target_area.Length; a++)
            {
                cmd += " `" + target_area[a] + "`=\"" + target[a] + "\" ";
                if (a == target_area.Length - 1) { cmd += "LIMIT 1;"; }
                else { cmd += "AND"; }
            }
            return cmd;
        }
        /// <summary>
        /// "UPDATE \"" + DB_Tabel_Name + "\" SET \"" + Edit_colum + "\"=\"" + Edit_Name + "\" WHERE \""+Search_Name+"\"=\"" + Search_Data + "\";"
        /// </summary>
        /// <param name="DB_Tabel_Name">테이블명</param>
        /// <param name="Edit_colum">수정할 컬럼명</param>
        /// <param name="Edit_Name">수정하고 싶은 문구</param>
        /// <param name="Search_Name">검색할 컬럼명</param>
        /// <param name="Search_Data">검색할 데이터</param>
        public string DB_Update(string DB_Tabel_Name, string Edit_colum, string Edit_Name, string Search_Name, string Search_Data)
        {
            string cmd = "UPDATE `" + DB_Tabel_Name + "` SET `" + Edit_colum + "`=\"" + Edit_Name + "\" WHERE `" + Search_Name + "`=\"" + Search_Data + "\";";
            cmd = cmd.Replace("|", "");
            return cmd;
        }
        /// <summary>
        /// 많은 곳의 데이터를 변화시키고 싶을때. 테이블명을 제외하곤 다 배열. Edit와 Search끼리의 배열 인덱스값이 각자 서로 같아야함.
        /// </summary>
        /// <param name="DB_Table_Name">바꿀 데이터가 있는 테이블명</param>
        /// <param name="Edit_col">대상 테이블명</param>
        /// <param name="Edit_name">바꿀 데이터값</param>
        /// <param name="Search_col">대상 테이블명</param>
        /// <param name="Search_Name">대상 데이터값</param>
        public string More_Update(String DB_Table_Name,
                        String[] Edit_col, String[] Edit_name,
                        String[] Search_col, String[] Search_Name, int limit = 0)
        {
            string cmd = "UPDATE `" + DB_Table_Name + "` SET ";
            for (int a = 0; a < Edit_col.Length; a++)
            {
                Edit_name[a] = Edit_name[a].Replace("\"", "\"\"");
                cmd += "`" + Edit_col[a] + "` = \"" + Edit_name[a] + "\"";
                if (a != Edit_col.Length - 1) { cmd += ", "; }
                else { cmd += " "; }
            }
            cmd += "WHERE ";
            for (int a = 0; a < Search_col.Length; a++)
            {
                cmd += "`" + Search_col[a] + "` = \"" + Search_Name[a] + "\" ";
                if (a != Search_col.Length - 1) { cmd += "AND "; }
            }
            if (limit != 0) { cmd += string.Format("LIMIT {0}", limit); }
            cmd += ";";
            cmd = cmd.Replace("|", "");
            return cmd;
        }
        /// <summary>
        /// DB에 회사이름을 검색하여 만약 있는 회사일 경우 False 반환 / 없을경우 True반환
        /// </summary>
        /// <param name="Search_Data">검색할 회사 명</param>
        /// <returns></returns>
        public string chk_comp(string CompName)
        {
            string cmd = "SELECT `idx` FROM `Comp`;";
            string result = "";
            // DB연결
            conn.Open();
            // 쿼리 맵핑
            sqlcmd.CommandText = cmd;
            // 쿼리 날릴 곳은 conn, 즉 아까 연결한 DB
            sqlcmd.Connection = conn;
            // 쿼리 날리기, sqlDataReader에 결과값 저장
            sd = sqlcmd.ExecuteReader();
            // 한줄씩 불러오기
            while (sd.Read())
            {
                for (int cout = 0; cout < sd.FieldCount; cout++)
                {
                    result = sd[cout].ToString();
                }
            }
            conn.Close();
            return result;
        }
        /// <summary>
        /// SQL문을 직접 만들어서 작성하여 사용해야함. (단, DELETE문/UPDATE문은 사용하지말 것!)
        /// </summary>
        /// <param name="cmd">등록할 SQL문</param>
        /// <returns></returns>
        public string self_Made_Cmd(string cmd)
        {
            cmd = cmd.Replace("|", "");

            string result = "";
            if (cmd.Contains("DELETE") == true || cmd.Contains("UPDATE") == true) { return ""; }
            conn.Open();
            try
            {
                sqlcmd.CommandText = cmd;
                sqlcmd.Connection = conn;
                sd = sqlcmd.ExecuteReader();
                while (sd.Read())
                {
                    for (int cout = 0; cout < sd.FieldCount; cout++)
                    {
                        result += sd[cout].ToString() + "|";
                    }
                }
            }
            catch (Exception e)
            {
                UTIL.MsgE(e.ToString());
            }
            conn.Close();
            return result;
        }

        #region 추가

        /// <summary>
        /// DBcon이 선진행되어야함. / SELECT * FROM DB_Table_Name WHERE DB_Where_Table = \"DB_Search_Data\";
        /// <summary>
        /// <param name="DB_Table_Name">테이블명</param>
        /// <param name="DB_Where_Table">검색할 테이블</param>
        /// <param name="DB_Search_Data">검색할 텍스트</param>
        /// <returns>검색된 결과값이 반환됨.</returns>
        public string DB_Search_Author(string DB_Table_Name, string Search_Area, string DB_Where_Table, string DB_Search_Data)
        {
            if (Search_Area == "") { Search_Area = "*"; }

            string result = "";
            // SELECT * FROM `Author_Symbol` WHERE `Author` <= '겐서' ORDER BY `Author` DESC LIMIT 1
            string cmd = string.Format("SELECT `{0}` FROM `{1}` WHERE `{2}` <= \'{3}\' ORDER BY `{2}` DESC LIMIT 1;",
                Search_Area, DB_Table_Name, DB_Where_Table, DB_Search_Data);

            // DB연결
            conn.Open();
            // 쿼리 맵핑
            sqlcmd.CommandText = cmd;
            // 쿼리 날릴 곳은 conn, 즉 아까 연결한 DB
            sqlcmd.Connection = conn;
            // 쿼리 날리기, sqlDataReader에 결과값 저장
            sd = sqlcmd.ExecuteReader();
            // 한줄씩 불러오기
            while (sd.Read())
            {
                for (int cout = 0; cout < sd.FieldCount; cout++)
                {
                    result += sd[cout].ToString() + "|";
                }
            }
            conn.Close();
            return result;
        }

        /// <summary>
        /// insert선 실행. 만약 값이 있을 경우 update로 전환
        /// </summary>
        /// <param name="Table"></param>
        /// <param name="InsertCol"></param>
        /// <param name="InsertData"></param>
        /// <returns></returns>
        public string DB_INSERT_DUPLICATE(string Table, string[] InsertCol, string[] InsertData)
        {
            string cmd = "INSERT INTO " + Table + "(";
            for (int a = 0; a < InsertCol.Length; a++)
            {
                if (a == InsertCol.Length - 1) { cmd += "`" + InsertCol[a] + "`) "; }
                else { cmd += "`" + InsertCol[a] + "`, "; }
            }
            cmd += "values(";
            for (int a = 0; a < InsertData.Length; a++)
            {
                InsertData[a] = InsertData[a].Replace("\"", "\"\"");
                if (a == InsertData.Length - 1) { cmd += "\"" + InsertData[a] + "\")"; }
                else { cmd += "\"" + InsertData[a] + "\", "; }
            }
            cmd = cmd.Replace("|", "");

            cmd += "ON DUPLICATE KEY UPDATE";

            string sub_cmd = "";
            for (int a = 0; a < InsertCol.Length; a++)
            {
                if (a == InsertCol.Length - 1)
                    sub_cmd += string.Format("`{0}` = \"{1}\";", InsertCol[a], InsertData[a]);
                else
                    sub_cmd += string.Format("`{0}` = \"{1}\",", InsertCol[a], InsertData[a]);
            }
            cmd += sub_cmd;

            return cmd;
        }
        #endregion
    }
}
