mysql批量上传数据

private object BlubckMysql(List<xiaoyao_blogs_pictureModel> list, string connect)
        {
            var sqllist = list.Select(item => string.Format(@"insert into xiaoyao_blogs_picture(classifyName,pictureUrl,pictureIntroduce,userName,addtime)values('{0}','{1}','{2}','{3}','{4}')", item.classifyName, item.pictureUrl, item.pictureIntroduce, item.userName, item.addtime)).ToList();
            using (var  conn = new MySqlConnection(connect))
            {
                conn.Open();
                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = conn;
                MySqlTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                try
                {
                    for (int n = 0; n < sqllist.Count; n++)
                    {
                        string strsql = sqllist[n].ToString();
                        if (strsql.Trim().Length > 1)
                        {
                            cmd.CommandText = strsql;
                           var a=cmd.ExecuteNonQuery();
                        }
                         //每500次开启一次事物
                        if (n > 0 && (n % 500 == 0 || n == sqllist.Count - 1))
                        {
                            tx.Commit();
                            tx = conn.BeginTransaction();
                        }
                    }                  
                }
                catch (System.Data.SqlClient.SqlException E)
                {
                    tx.Rollback(); throw new Exception(E.Message);
                }
            }
            return null;
        }

 

posted @ 2015-08-11 14:13  逍遥帝君  阅读(748)  评论(0编辑  收藏  举报