SqlGenerate.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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="splitLine">按VALUES分割行</param>
  21. /// <param name="spaceLine">每行间隔空行</param>
  22. /// <param name="insertSql">插入语句,默认:INSERT INTO,可自定义为:INSERT IGNORE INTO</param>
  23. /// <returns></returns>
  24. public static List<string> Insert(string tableName, DataTable table, bool splitLine = false, bool spaceLine = false, string insertSql = "INSERT INTO")
  25. {
  26. if (!StringTool.Ok(insertSql)) insertSql = "INSERT INTO";
  27. List<string> list = new List<string>();
  28. if (DataTableTool.Ok(table))
  29. {
  30. // 获取所有列名
  31. List<string> colNameList = new List<string>();
  32. for (int i = 0; i < table.Columns.Count; i++)
  33. {
  34. DataColumn column = table.Columns[i];
  35. if (StringTool.Ok(column.ColumnName)) colNameList.Add(column.ColumnName);
  36. }
  37. // 遍历所有行,转换为插入语句
  38. for (int j = 0; j < table.Rows.Count; j++)
  39. {
  40. DataRow row = table.Rows[j];
  41. string cols = "", vals = "";
  42. for (int k = 0; k < colNameList.Count; k++)
  43. {
  44. string value = DataRowTool.GetValueWithNull(row, colNameList[k]);
  45. cols += $"`{colNameList[k]}`";
  46. if (k < colNameList.Count - 1) cols += ", ";
  47. vals += value != null ? $"'{value}'" : "NULL";
  48. if (k < colNameList.Count - 1) vals += ", ";
  49. }
  50. string _splitLine = splitLine ? Environment.NewLine : "";
  51. string _spaceLine = spaceLine ? Environment.NewLine : "";
  52. string sql = $"{insertSql} `{tableName}` ({cols}) {_splitLine}VALUES ({vals});{_spaceLine}";
  53. list.Add(sql);
  54. }
  55. }
  56. return list;
  57. }
  58. }
  59. }