SqlGenerate.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using Azylee.Core.DataUtils.DataTableUtils;
  2. using Azylee.Core.DataUtils.StringUtils;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Data;
  6. using System.Linq;
  7. using System.Text;
  8. namespace Azylee.Core.DbUtils.DbSqls
  9. {
  10. /// <summary>
  11. /// Sql语句生成
  12. /// </summary>
  13. public static class SqlGenerate
  14. {
  15. /// <summary>
  16. /// 生成insert语句
  17. /// </summary>
  18. /// <param name="tableName">表名</param>
  19. /// <param name="table">数据表</param>
  20. /// <param name="insertSql">插入语句,默认:INSERT INTO,可自定义为:INSERT IGNORE INTO</param>
  21. /// <param name="splitLine">按VALUES分割行</param>
  22. /// <param name="spaceLine">每行间隔空行</param>
  23. /// <returns></returns>
  24. public static List<string> Insert(string tableName, DataTable table, string insertSql = "INSERT INTO", bool splitLine = false, bool spaceLine = false)
  25. {
  26. List<string> list = new List<string>();
  27. if (DataTableTool.Ok(table))
  28. {
  29. // 获取所有列名
  30. List<string> colNameList = new List<string>();
  31. for (int i = 0; i < table.Columns.Count; i++)
  32. {
  33. DataColumn column = table.Columns[i];
  34. if (StringTool.Ok(column.ColumnName)) colNameList.Add(column.ColumnName);
  35. }
  36. // 遍历所有行,转换为插入语句
  37. for (int j = 0; j < table.Rows.Count; j++)
  38. {
  39. DataRow row = table.Rows[j];
  40. string cols = "", vals = "";
  41. for (int k = 0; k < colNameList.Count; k++)
  42. {
  43. string value = DataRowTool.GetValueWithNull(row, colNameList[k]);
  44. cols += $"`{colNameList[k]}`";
  45. if (k < colNameList.Count - 1) cols += ", ";
  46. vals += value != null ? $"'{value}'" : "NULL";
  47. if (k < colNameList.Count - 1) vals += ", ";
  48. }
  49. string _splitLine = splitLine ? Environment.NewLine : "";
  50. string _spaceLine = spaceLine ? Environment.NewLine : "";
  51. string sql = $"{insertSql} `{tableName}` ({cols}) {_splitLine}VALUES ({vals});{_spaceLine}";
  52. list.Add(sql);
  53. }
  54. }
  55. return list;
  56. }
  57. }
  58. }