将 Excel 数据导入 MySql

能承受上万数据量,速度快,并且使用了事务,不会出现某条数据错误而导致部分数据插入(要是全部成功要是一条都不成功,测试过程中没出现失败),需要的朋友可以参考下

 

1.NPOI

2.MySql.Data

这里做个记录,待日后使用

效果图

 

 

技术分享     技术分享

 

连接字符串 app.config:

 <connectionStrings>
    <add name="DBConnectString" connectionString="Server=ip;Database=testjh;Uid=user;Pwd=123456;charset=utf8" providerName="MySql.Data.MySqlClient"/>
  </connectionStrings>

 

执行多条sql语句:

        /// <summary>
        /// 执行多条SQL语句,实现数据库事务。
        /// </summary>mysql数据库
        /// <param name="SQLStringList">多条SQL语句</param>
        public static void ExecuteSqlTran(List<string> SQLStringList)
        {
            using (MySqlConnection conn = new MySqlConnection(MySqlHelper.connectionString))
            {
                conn.Open();
                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = conn;
                MySqlTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                try
                {
                    for (int n = 0; n < SQLStringList.Count; n++)
                    {
                        string strsql = SQLStringList[n].ToString();
                        if (strsql.Trim().Length > 1)
                        {
                            cmd.CommandText = strsql;
                            cmd.ExecuteNonQuery();
                        }
                        //后来加上的
                        if (n > 0 && (n % 500 == 0 || n == SQLStringList.Count - 1))
                        {
                            tx.Commit();
                            tx = conn.BeginTransaction();
                        }
                    }
                    //tx.Commit();//原来一次性提交
                }
                catch (System.Data.SqlClient.SqlException E)
                {
                    tx.Rollback();
                    throw new Exception(E.Message);
                }
            }
        }

  

单击按钮:

        /// <summary>
        /// 单击按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            button1.Text = "正在插入中...";
            OpenFileDialog file1 = new OpenFileDialog();
            file1.Filter = "Excel文件|*.xlsx";
            if (file1.ShowDialog() == DialogResult.OK)
            {
                //开始读excel
                Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); ;
                Microsoft.Office.Interop.Excel.Workbook workbook = xlApp.Workbooks.Open(file1.FileName, 0, false, 5, "", "",false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, 1, 0);
                int n = workbook.Worksheets.Count;
                string[] sheetSet = new string[n];
                ArrayList al = new ArrayList();
                for (int i = 0; i < n; i++)
                {
                    sheetSet[i] = ((Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[i + 1]).Name;
                }
                xlApp.Workbooks.Close();


                ExcelHelper ex = new ExcelHelper(file1.FileName);
                if (sheetSet.Length > 0)//判断存在 一个 Sheet1
                {
                    int countLength = sheetSet.Length;//表示 Sheet的个数
                    dt1 = ex.ExcelToDataTable(sheetSet[0], true);//"Sheet1" ,先假如只有一个Sheet1     
                    insertMySql();
                }
            }

        }

写入数据:

public void insertMySql()
        {
            try
            {
                int ColumnsCount = dt1.Columns.Count;//得到读出表中 列的数量
                string str = string.Empty;
                string[] strArr = new string[ColumnsCount];
                string valuesStr = string.Empty;
                List<string> listStr=new List<string>();                

                for (int i = 0; i < dt1.Rows.Count; i++)
                {
                    DataRow dr = dt1.Rows[i];

                    for (int j = 0; j < ColumnsCount; j++)
                    {
                        strArr[j] = dr.ItemArray[j].ToString();
                    }
                    string sqlInsert =string.Format("insert into t_test(torder,tname,stu_num,tage) values(‘{0}‘,‘{1}‘,‘{2}‘,‘{3}‘)",strArr[0],strArr[1],strArr[2],strArr[3]);
                    listStr.Add(sqlInsert);
                    #region 没使用事务
                    
                    //string sql = "insert into t_test(torder,tname,stu_num,tage) values(@torder,@tname,@stu_num,@tage)";
                    //MySqlParameter[] parms = { 
                    //                     new MySqlParameter("@torder",strArr[0]),
                    //                     new MySqlParameter("@tname",strArr[1]),
                    //                     new MySqlParameter("@stu_num",strArr[2]),
                    //                     new MySqlParameter("@tage",strArr[3])
                    //                     };
                    // 在这里可以直接调用 ExecuteNonQuery 向数据库插数据
                  //  MySqlHelper.ExecuteNonQuery(MySqlHelper.connectionString, CommandType.Text, sql, parms);
                    #endregion
                }
                ExecuteSqlTran(listStr);//使用事务插入
              //  button1.Text = "插入成功!";
                Thread.Sleep(10000);
                button1.Text = "插入成功,请选择Excel文件!";
            }
            catch (Exception ex)
            {
                
                throw ex;
            }
          
        }

MySqlHelper:  应该把   ExecuteSqlTran 这个类方法放入该类,这里我没有这么做,项目小(零时需求)就没这么做了!

public static string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DBConnectString"].ToString();

  

 

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。