Home  >  Article  >  Database  >  [转载]mysql插入大量数据_MySQL

[转载]mysql插入大量数据_MySQL

WBOY
WBOYOriginal
2016-06-01 13:32:37851browse

bitsCN.com

mysql的批量数据格式,

比如
INSERT INTO TABLES (LABLE1,LABLE2,LABLE3,...) 
VALUES(NUM11,NUM12,NUM13,...), 
(NUM21,NUM22,NUM23,...),
....
(NUMn1,NUMn2,NUMn3,..);

我在前文中叙述的,每个账户的每个采集点就会生成几百个数据,这几百个数据我组合成上述一条语句,20多个账户多个采集点我一共生成上述语句300--800多条,每条的数据项300-500个,所以每次插入的数据共计10000--50000条。

我把每条insert语句都保存在一个SQLStringList之中,又 在网上找点资料,采用了事务处理方式,本来我的事务方式是所有sql语句放在一个事务里,但有热心朋友告知“每当执行1000条DBCommand就提交(Commit)事务,然后再次开启事务,这样比较好。把过多的命令放在一个事务中,一旦超过物理内存分配限制,你的程序会变得很慢很慢。”

所以我后来修改了一下,每500条语句重启一次事务。c#代码如下:

   1:          public static void ExecuteSqlTran(List<string> SQLStringList)  
   2:          {  
   3:              using (MySqlConnection conn = new MySqlConnection(MySqlHelper.ConnStr))  
   4:              {  
   5:                  conn.Open();  
   6:                  MySqlCommand cmd = new MySqlCommand();  
   7:                  cmd.Connection = conn;  
   8:                  MySqlTransaction tx = conn.BeginTransaction();  
   9:                  cmd.Transaction = tx;  
  10:                  try
  11:                  {  
  12:                      for (int n = 0; n   <pre class="alt">  13:                      {  
  14:                          string strsql = SQLStringList[n].ToString();  
  15:                          if (strsql.Trim().Length > 1)  
  16:                          {  
  17:                              cmd.CommandText = strsql;  
  18:                              cmd.ExecuteNonQuery();  
  19:                          }  
  20:                          //后来加上的
  21:                          if (n > 0 && (n % 500 == 0 || n == SQLStringList.Count - 1))  
  22:                          {  
  23:                              tx.Commit();  
  24:                              tx = conn.BeginTransaction();  
  25:                          }  
  26:                      }  
  27:                      //tx.Commit();//原来一次性提交
  28:                  }  
  29:                  catch (System.Data.SqlClient.SqlException E)  
  30:                  {  
  31:                      tx.Rollback();  
  32:                      throw new Exception(E.Message);  
  33:                  }  
  34:              }  
  35:          }  
bitsCN.com
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn