C# DataTable 生成 SQL INSERT 语句
作者:互联网
/// <summary>
/// 将Datatable转换为InsertSql
/// </summary>
/// <param name="dt">数据源</param>
/// <param name="table">表名称</param>
/// <returns></returns>public static List<string> DataTableToInsertSql(DataTable dt, string table)
{
List<string> result = new List<string>();string cols = string.Join(",", dt.Columns.Cast<DataColumn>().Select(x => $"[{x.ColumnName}]").ToArray());
foreach (DataRow dr in dt.Rows)
{
var vals = string.Join(",", dr.ItemArray.Select(x =>
{
if (DBNull.Value.GetType() == x.GetType())
{
return "null";
}
else
{
return $"'{x}'";
}
}).ToArray());result.Add($"insert into {table} ({cols}) values({vals})");
}return result;
}
标签:INSERT,return,string,ToArray,C#,List,result,SQL,dt 来源: https://blog.csdn.net/make1828/article/details/110442306