C#读取Txt大数据并更新到数据库

环境

Sqlserver 2016

.net 4.5.2

目前测试数据1300万 大约3-4分钟.(限制一次读取条数 和 线程数是 要节省服务器资源,如果调太大服务器其它应用可能就跑不了了), SqlServerDBHelper为数据库帮助类.没有什么特别的处理. 配置连接串时记录把连接池开起来

另外.以下代码中每次写都创建了连接 .之前试过一个连接反复用. 130次大约有20多次 数据库会出问题.并且需要的时间是7-8分钟 左右.

配置文件: xxx.json

 
 
  1. [ {
  2. /*连接字符串 */
  3. "ConnStr": "",
  4. "FilePath": "读取的文件地址",
  5. /*数据库表名称 */
  6. "TableName": "写入的数据库表名",
  7. /*导入前执行的语句 */
  8. "ExecBeforeSql": "",
  9. /*导入后执行的语句 */
  10. "ExecAfterSql": "",
  11. /*映射关系 */
  12. "Mapping": [
  13. {
  14. "DBName": "XXX",
  15. "TxtName": "DDD"
  16. }
  17. ],
  18. /*过滤数据的正则 当前只实现了小数据一次性读完的检查*/
  19. "FilterRegex": [],
  20. /*检查数据合法性(从数据库获取字段属性进行验证) */
  21. "CheckData": false,
  22. /*列分隔符*/
  23. "Separator": "\t",
  24. /*表头的行数*/
  25. "HeaderRowsNum": 1
  26. }
  27. ]

读取代码 : 注意 ConfigurationManager.AppSettings["frpage"] 和 ConfigurationManager.AppSettings["fr"] 需要自己配置好

 
 
  1. //读取配置文件信息
  2. List<dynamic> dt = JsonConvert.DeserializeObject<List<dynamic>>(File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config\\ImportTxt.json")));
  3. LogUtil.Info("开始读取txt数据,读取配置:" + dt.Count + "条");
  4. if (dt.Count == )
  5. {
  6. return;
  7. }
  8. List<Task> li = new List<Task>();
  9. foreach (dynamic row in dt)
  10. {
  11. LogUtil.Info("开始处理数据:" + JsonConvert.SerializeObject(row));
  12. li.Add(ProcessRow(row));
  13. }
  14. Task.WaitAll(li.ToArray());
  15. LogUtil.Info("数据读取完毕");
 
 
  1. public async Task ProcessRow(dynamic row)
  2. {
  3. await Task.Run(() =>
  4. {
  5. AutoResetEvent AE = new AutoResetEvent(false);
  6. DataTable Data = null;
  7. string error = "", ConnStr, TableName, ExecBeforeSql, ExecAfterSql;
  8. Boolean IsCheck = Convert.ToBoolean(row["CheckData"]);
  9. TableName = Convert.ToString(row.TableName);
  10. ConnStr = Convert.ToString(row.ConnStr);
  11. ExecBeforeSql = Convert.ToString(row.ExecBeforeSql);
  12. ExecAfterSql = Convert.ToString(row.ExecAfterSql);
  13. int HeaderRowsNum = Convert.ToInt32(row.HeaderRowsNum);
  14. string Separator = Convert.ToString(row.Separator);
  15. Dictionary<string, string> dic = new Dictionary<string, string>();
  16. //文件达到多大时就分行读取
  17. int fr = ;
  18. if (!int.TryParse(ConfigurationManager.AppSettings["fr"], out fr))
  19. {
  20. fr = ;
  21. }
  22. fr = fr * * ;
  23. //分行读取一次读取多少
  24. int page = ;
  25. if (!int.TryParse(ConfigurationManager.AppSettings["frpage"], out page))
  26. {
  27. page = ;
  28. }
  29. foreach (var dyn in row.Mapping)
  30. {
  31. dic.Add(Convert.ToString(dyn.TxtName), Convert.ToString(dyn.DBName));
  32. }
  33. List<string> regex = new List<string>();
  34. foreach (string item in row["FilterRegex"])
  35. {
  36. regex.Add(item);
  37. }
  38. string fpath = "", cpath = "";
  39. cpath = Convert.ToString(row["FilePath"]);
  40. string rootPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp");
  41. if (!Directory.Exists(rootPath))
  42. {
  43. Directory.CreateDirectory(rootPath);
  44. }
  45. fpath = Path.Combine(rootPath, Path.GetFileName(cpath));
  46. File.Copy(cpath, fpath, true);
  47. LogUtil.Info("拷文件到本地已经完成.从本地读取数据操作");
  48. int threadCount = Environment.ProcessorCount * ;
  49. FileInfo fi = new FileInfo(fpath);
  50. //如果文件大于100M就需要分批读取.一次50万条
  51. if (fi.Length > fr)
  52. {
  53. long sumCount = ;
  54. StreamReader sr = new StreamReader(fi.OpenRead());
  55. int headRow = ;
  56. string rowstr = "";
  57. List<Thread> li_th = new List<Thread>();
  58. bool last = false;
  59. int ij = ;
  60. LogUtil.Info("生成StreamReader成功 ");
  61. #region 逐行读取
  62. while (sr.Peek() > -)
  63. {
  64. rowstr = sr.ReadLine();
  65. #region 将行数据写入DataTable
  66. if (headRow < HeaderRowsNum)
  67. {
  68. Data = new DataTable();
  69. foreach (string scol in rowstr.Split(new string[] { Separator }, StringSplitOptions.RemoveEmptyEntries))
  70. {
  71. Data.Columns.Add(scol.Trim(), typeof(string));
  72. }
  73. headRow++;
  74. continue;
  75. }
  76. else
  77. { //行数据
  78. if (headRow > )
  79. {
  80. for (int i = ; i < headRow && sr.Peek() > -; i++)
  81. {
  82. rowstr += " " + sr.ReadLine();
  83. }
  84. }
  85. Data.Rows.Add(rowstr.Split(new string[] { Separator }, StringSplitOptions.RemoveEmptyEntries));
  86. if (Data.Rows.Count < page && sr.Peek() > -)
  87. {
  88. continue;
  89. }
  90. }
  91. last = (sr.Peek() == -);
  92. #endregion
  93. sumCount += Data.Rows.Count;
  94. ProcessPath(Data, page, sr, ref ij, TableName, ExecBeforeSql, ExecAfterSql, dic, IsCheck, li_th);
  95. #region 检查线程等待
  96. if ((ij > && (ij % threadCount) == ) || last)
  97. {
  98. LogUtil.Info("完成一批次当前共写数据: " + sumCount);
  99. while (true)
  100. {
  101. bool isok = true;
  102. foreach (var item in li_th)
  103. {
  104. if (item.IsAlive)
  105. {
  106. isok = false;
  107. Application.DoEvents();
  108. Thread.Sleep();
  109. }
  110. }
  111. if (isok)
  112. {
  113. li_th.Clear();
  114. break;
  115. }
  116. }
  117. //最后一页要等所有的执行完才能执行
  118. if (sr.Peek() == -)
  119. {
  120. WriteTODB(TableName, Data, ExecBeforeSql, ExecAfterSql, dic, false, true);
  121. LogUtil.Info("最后一次写入完成");
  122. }
  123. LogUtil.Info(" 线程退出开始新的循环...");
  124. }
  125. Data.Clear();
  126. #endregion
  127. }
  128. sr.Dispose();
  129. #endregion
  130. }
  131. else
  132. {
  133. using (SQLServerDBHelper sdb = new SQLServerDBHelper())
  134. {
  135. sdb.OpenConnection();
  136. #region 一次性读取处理
  137. Data = LoadDataTableFromTxt(fpath, ref error, Separator, HeaderRowsNum, regex, IsCheck, dic, TableName);
  138. if (IsCheck)
  139. {
  140. DataRow[] rows = Data.Select("ErrorMsg is not null");
  141. if (rows.Length > )
  142. {
  143. LogUtil.Info($"读取{TableName} 数据出错 : {JsonConvert.SerializeObject(rows)}");
  144. return;
  145. }
  146. }
  147. LogUtil.Info($"读取{TableName} 的txt数据完成.共读取数据:{Data.Rows.Count}条");
  148. if (Data.Rows.Count == || !string.IsNullOrWhiteSpace(error))
  149. {
  150. if (!string.IsNullOrWhiteSpace(error))
  151. {
  152. LogUtil.Info("读取数据出错,地址:" + Convert.ToString(row["FilePath"]) + " \r\n 错误:" + error);
  153. }
  154. return;
  155. }
  156. sdb.BgeinTransaction();
  157. try
  158. {
  159. WriteTODB(TableName, Data, ExecBeforeSql, ExecAfterSql, dic, sdb: sdb);
  160. sdb.CommitTransaction();
  161. LogUtil.Info(TableName + "数据更新完毕 !!");
  162. }
  163. catch (Exception ex)
  164. {
  165. LogUtil.Info(TableName + " 更新数据出错,错误:" + ex.Message + " \r\n 堆栈:" + ex.StackTrace);
  166. sdb.RollbackTransaction();
  167. }
  168. #endregion
  169. }
  170. }
  171. GC.Collect();
  172. });
  173. }
  174. private void ProcessPath(DataTable Data, int page, StreamReader sr, ref int ij, string TableName, string ExecBeforeSql, string ExecAfterSql, Dictionary<string, string> dic, bool IsCheck, List<Thread> li_th)
  175. {
  176. int threadCount = Environment.ProcessorCount * ;
  177. string error = "";
  178. PoolModel p = new PoolModel { TableName = TableName, ExecBeforeSql = ExecBeforeSql, ExecAfterSql = ExecAfterSql, dic = dic };
  179. p.Data = Data.Copy();
  180. if (IsCheck)
  181. {
  182. using (SQLServerDBHelper sdb = new SQLServerDBHelper())
  183. {
  184. error = CheckData(Data, TableName, dic, sdb);
  185. }
  186. DataRow[] rows = Data.Select("ErrorMsg is not null");
  187. if (rows.Length > || !string.IsNullOrWhiteSpace(error))
  188. {
  189. LogUtil.Info($"读取{TableName} 数据出错 : {JsonConvert.SerializeObject(rows)}\r\n错误: " + error);
  190. return;
  191. }
  192. }
  193. ij++;
  194. if (ij == )
  195. {
  196. WriteTODB(p.TableName, p.Data, p.ExecBeforeSql, p.ExecAfterSql, p.dic, true, false);
  197. LogUtil.Info("首次写入完成");
  198. }
  199. else if (sr.Peek() > -)
  200. {
  201. Thread t = new Thread(d =>
  202. {
  203. PoolModel c = d as PoolModel;
  204. try
  205. {
  206. WriteTODB(c.TableName, c.Data, c.ExecBeforeSql, c.ExecAfterSql, c.dic, false, false);
  207. }
  208. catch (ThreadAbortException)
  209. {
  210. LogUtil.Error("线程退出.................");
  211. }
  212. catch (Exception ex)
  213. {
  214. LogUtil.Error(c.TableName + "写入数据失败:" + ex.Message + "\r\n堆栈:" + ex.StackTrace + "\r\n 数据: " + JsonConvert.SerializeObject(c.Data));
  215. ExitApp();
  216. return;
  217. }
  218. });
  219. t.IsBackground = true;
  220. t.Start(p);
  221. li_th.Add(t);
  222. }
  223. }
  224. public void ExitApp()
  225. {
  226. Application.Exit();
  227. }
  228. public void WriteTODB(string TableName, DataTable Data, string ExecBeforeSql, string ExecAfterSql, Dictionary<string, string> dic, bool first = true, bool last = true, SQLServerDBHelper sdb = null)
  229. {
  230. bool have = false;
  231. if (sdb == null)
  232. {
  233. sdb = new SQLServerDBHelper();
  234. have = true;
  235. }
  236. if (first && !string.IsNullOrWhiteSpace(ExecBeforeSql))
  237. {
  238. LogUtil.Info(TableName + "执行前Sql :" + ExecBeforeSql);
  239. sdb.ExecuteNonQuery(ExecBeforeSql);
  240. }
  241. sdb.BulkCopy(Data, TableName, dic);
  242. if (last && !string.IsNullOrWhiteSpace(ExecAfterSql))
  243. {
  244. LogUtil.Info(TableName + "执行后Sql :" + ExecAfterSql);
  245. sdb.ExecuteNonQuery(ExecAfterSql);
  246. }
  247. LogUtil.Info(TableName + "本次执行完成 ");
  248. if (have)
  249. {
  250. sdb.Dispose();
  251. }
  252. }
  253. public string CheckData(DataTable dt, string dbTableName, Dictionary<string, string> dic, SQLServerDBHelper sdb)
  254. {
  255. if (string.IsNullOrWhiteSpace(dbTableName))
  256. {
  257. return "表名不能为空!";
  258. }
  259. if (dic.Count == )
  260. {
  261. return "映射关系数据不存在!";
  262. }
  263. List<string> errorMsg = new List<string>();
  264. List<string> Cols = new List<string>();
  265. dic.Foreach(c =>
  266. {
  267. if (!dt.Columns.Contains(c.Key))
  268. {
  269. errorMsg.Add(c.Key);
  270. }
  271. Cols.Add(c.Key);
  272. });
  273. if (errorMsg.Count > )
  274. {
  275. return "数据列不完整,请与映射表的数据列数量保持一致!列:" + string.Join(",", errorMsg);
  276. }
  277. //如果行数据有错误信息则添加到这一列的值里
  278. dt.Columns.Add(new DataColumn("ErrorMsg", typeof(string)) { DefaultValue = "" });
  279. string sql = @"--获取SqlServer中表结构
  280. SELECT syscolumns.name as ColName,systypes.name as DBType,syscolumns.isnullable,
  281. syscolumns.length
  282. FROM syscolumns, systypes
  283. WHERE syscolumns.xusertype = systypes.xusertype
  284. AND syscolumns.id = object_id(@tb) ; ";
  285. DataSet ds = sdb.GetDataSet(sql, new SqlParameter[] { new SqlParameter("@tb", dbTableName) });
  286. EnumerableRowCollection<DataRow> TableDef = ds.Tables[].AsEnumerable();
  287. // string colName="";
  288. Object obj_val;
  289. //将表结构数据重组成字典.
  290. var dic_Def = TableDef.ToDictionary(c => Convert.ToString(c["ColName"]), d =>
  291. {
  292. string DBType = "";
  293. string old = Convert.ToString(d["DBType"]).ToUpper();
  294. DBType = GetCSharpType(old);
  295. return new { ColName = Convert.ToString(d["ColName"]), DBType = DBType, SqlType = old, IsNullble = Convert.ToBoolean(d["isnullable"]), Length = Convert.ToInt32(d["length"]) };
  296. });
  297. DateTime now = DateTime.Now;
  298. foreach (DataRow row in dt.Rows)
  299. {
  300. errorMsg.Clear();
  301. foreach (string colName in Cols)
  302. {
  303. if (dic.ContainsKey(colName))
  304. {
  305. if (!dic_Def.ContainsKey(dic[colName]))
  306. {
  307. return "Excel列名:" + colName + " 映射数据表字段:" + dic[colName] + "在当前数据表中不存在!";
  308. }
  309. //去掉数据两边的空格
  310. row[colName] = obj_val = Convert.ToString(row[colName]).Trim();
  311. var info = dic_Def[dic[colName]];
  312. //是否是DBNULL
  313. if (obj_val.Equals(DBNull.Value))
  314. {
  315. if (!info.IsNullble)
  316. {
  317. errorMsg.Add("列" + colName + "不能为空!");
  318. }
  319. }
  320. else
  321. {
  322. if (info.DBType == "String")
  323. {
  324. //time类型不用验证长度(日期的 时间部分如 17:12:30.0000)
  325. if (info.SqlType == "TIME")
  326. {
  327. if (!DateTime.TryParse(now.ToString("yyyy-MM-dd") + " " + obj_val.ToString(), out now))
  328. {
  329. errorMsg.Add("列" + colName + "填写的数据无效应为日期的时间部分如:17:30:12");
  330. }
  331. }
  332. else if (Convert.ToString(obj_val).Length > info.Length)
  333. {
  334. errorMsg.Add("列" + colName + "长度超过配置长度:" + info.Length);
  335. }
  336. }
  337. else
  338. {
  339. Type t = Type.GetType("System." + info.DBType);
  340. try
  341. { //如果数字中有千分位在这一步可以处理掉重新给这个列赋上正确的数值
  342. row[colName] = Convert.ChangeType(obj_val, t); ;
  343. }
  344. catch (Exception ex)
  345. {
  346. errorMsg.Add("列" + colName + "填写的数据" + obj_val + "无效应为" + info.SqlType + "类型.");
  347. }
  348. }
  349. }
  350. }
  351. }
  352. row["ErrorMsg"] = string.Join(" || ", errorMsg);
  353. }
  354. return "";
  355. }
  356. /// <summary>
  357. /// wm 2018年11月28日13:37
  358. /// 将数据库常用类型转为C# 中的类名(.Net的类型名)
  359. /// </summary>
  360. /// <param name="old"></param>
  361. /// <returns></returns>
  362. private string GetCSharpType(string old)
  363. {
  364. string DBType = "";
  365. switch (old)
  366. {
  367. case "INT":
  368. case "BIGINT":
  369. case "SMALLINT":
  370. DBType = "Int32";
  371. break;
  372. case "DECIMAL":
  373. case "FLOAT":
  374. case "NUMERIC":
  375. DBType = "Decimal";
  376. break;
  377. case "BIT":
  378. DBType = "Boolean";
  379. break;
  380. case "TEXT":
  381. case "CHAR":
  382. case "NCHAR":
  383. case "VARCHAR":
  384. case "NVARCHAR":
  385. case "TIME":
  386. DBType = "String";
  387. break;
  388. case "DATE":
  389. case "DATETIME":
  390. DBType = "DateTime";
  391. break;
  392. default:
  393. throw new Exception("GetCSharpType数据类型" + DBType + "无法识别!");
  394. }
  395. return DBType;
  396. }
  397. public class PoolModel
  398. {
  399. public string TableName { get; set; }
  400. public DataTable Data { get; set; }
  401. public string ExecBeforeSql { get; set; }
  402. public string ExecAfterSql { get; set; }
  403. public Dictionary<string, string> dic { get; set; }
  404. }
 
 
  1. /// <summary>
  2. /// wm 2018年11月28日13:32
  3. /// 获取Txt数据并对数据进行校验返回一个带有ErrorMsg列的DataTable,如果数据校验失败则该字段存放失败的原因
  4. /// 注意:在使用该方法前需要数据表应该已经存在
  5. /// </summary>
  6. /// <param name="isCheck">是否校验数据合法性(数据需要校验则会按传入的dbTableName获取数据库表的结构出来验证)</param>
  7. /// <param name="map">如果需要验证数据则此处需要传映射关系 key Excel列名,Value 数据库列名</param>
  8. /// <param name="dbTableName">验证数据合法性的表(即数据会插入到的表)</param>
  9. /// <param name="error">非数据验证上的异常返回</param>
  10. /// <param name="Regexs">用来过滤数据的正则</param>
  11. /// <param name="path">读取文件的路径</param>
  12. /// <param name="Separator">列分隔符</param>
  13. /// <param name="HeaderRowsNum">表头的行数</param>
  14. /// <returns>如果需求验证则返回一个带有ErrorMsg列的DataTable,如果数据校验失败则该字段存放失败的原因, 不需要验证则数据读取后直接返回DataTable</returns>
  15. public DataTable LoadDataTableFromTxt(string path, ref string error, string Separator, int HeaderRowsNum, List<string> Regexs = null, bool isCheck = false, Dictionary<string, string> map = null, string dbTableName = "", SQLServerDBHelper sdb = null)
  16. {
  17. DataTable dt = new DataTable();
  18. error = "";
  19. if (isCheck && (map == null || map.Count == || string.IsNullOrWhiteSpace(dbTableName)))
  20. {
  21. error = "参数标明需要对表格数据进行校验,但没有指定映射表集合或数据表名.";
  22. return dt;
  23. }
  24. string txts = File.ReadAllText(path);
  25. #region 把读出来的方便数据转成DataTable
  26. Regexs?.ForEach(c =>
  27. {
  28. txts = new Regex(c).Replace(txts, "");
  29. });
  30. 替换掉多表的正则
  31. //Regex mu_re = new Regex(@"\+[-+]{4,}\s+\+[-+\s|\w./]{4,}\+"); //FTP new Regex(@"\+[-+]{4,}\s+\+[-+\s|\w./]{4,}\+"); //原来以-分隔的 new Regex(@"-{5,}(\s)+-{5,}\s+\|.+(\s)?\|.+(\s)?\|-{5,}");
  32. 去掉所有横线
  33. //Regex mu_r = new Regex(@"[+-]{4,}"); //FTP new Regex(@"[+-]{4,}"); //原 new Regex(@"(\|-{5,})|(-{5,})");
  34. //string s1 = mu_re.Replace(txts, "");
  35. //string s2 = mu_r.Replace(s1, "");
  36. // string[] tts = s2.Split(new string[] { "\r\n" }, StringSplitOptions.None);
  37. string[] tts = txts.Split(new string[] { "\r\n" }, StringSplitOptions.None);
  38. string[] vals;
  39. string s1;
  40. //生成表头默认第一行时表头直到遇到第一个只有一个|的内容为止(有几行表头,下面的内容就会有几行)
  41. int headerNum = -;//记录表头有几列
  42. DataRow dr;
  43. //处理col重复的问题,如果有重复按第几个来命名 比如 A1 A2
  44. Dictionary<string, int> col_Rep = new Dictionary<string, int>();
  45. string colName = "";
  46. bool isre = false;//记录当前是否有重复列
  47. int empty_HeaderRow = ;
  48. for (int i = ; i < tts.Length; i++)
  49. {
  50. s1 = tts[i];
  51. //还未获取出表头
  52. if (headerNum < HeaderRowsNum)
  53. {
  54. vals = s1.Split(new string[] { Separator }, StringSplitOptions.RemoveEmptyEntries);
  55. foreach (string col in vals)
  56. {
  57. colName = col.Trim();
  58. if (col_Rep.Keys.Contains(colName))
  59. {
  60. col_Rep[colName]++;
  61. isre = true;
  62. //重复列处理
  63. //colName += col_Rep[colName];
  64. continue;
  65. }
  66. else
  67. {
  68. col_Rep.Add(colName, );
  69. }
  70. dt.Columns.Add(colName, typeof(string));
  71. }
  72. headerNum = (i == (HeaderRowsNum - )) ? HeaderRowsNum : ;
  73. }
  74. else
  75. {
  76. if (string.IsNullOrWhiteSpace(s1.Trim()) || string.IsNullOrWhiteSpace(s1.Replace(Separator, "")))
  77. {
  78. continue;
  79. }
  80. if (isre)
  81. {
  82. error = "列:" + string.Join(",", col_Rep.Where(c => c.Value > ).Select(c => c.Key)) + "存在重复";
  83. return dt;
  84. }
  85. //多行时把多行的数据加在一起处理
  86. if (headerNum > )
  87. {
  88. for (int j = ; j < headerNum && (i + j) < tts.Length; j++)
  89. {
  90. //数据第一行最后没有| 如果没数据则直接换行了所以这里补一个空格防止数据被当空数据移除了
  91. s1 += " " + tts[i + j];
  92. }
  93. }
  94. vals = s1.Split(new string[] { Separator }, StringSplitOptions.RemoveEmptyEntries);
  95. dr = dt.NewRow();
  96. dr.ItemArray = vals;
  97. dt.Rows.Add(dr);
  98. //因为本次循环结束上面会去++ 所以这里只加headerNum-1次
  99. i += (headerNum - );
  100. }
  101. }
  102. #endregion
  103. if (isCheck)
  104. {
  105. //dt.Columns.Remove("Item");
  106. //dt.Columns["Item1"].ColumnName = "Item";
  107. //dt.Columns.RemoveAt(dt.Columns.Count - 2);
  108. error = CheckData(dt, dbTableName, map, sdb);
  109. }
  110. return dt;
  111. }

猜你喜欢

转载自blog.csdn.net/zxj19880502/article/details/129179751