C# 根据datatable,生成sql insert语句
比如INSERTINTO`"+dtName+"`(`column1.name`,`columb2.name`,....,`column3.name`)values('"+...
比如
INSERT INTO `" + dtName + "` (`column1.name`, `columb2.name`, ....,`column3.name`) values ('" + Convert.ToString(row[0]) + "','" + Convert.ToString(row[1]) + "','" +....+ Convert.ToString(row[n-1]) + "') 展开
INSERT INTO `" + dtName + "` (`column1.name`, `columb2.name`, ....,`column3.name`) values ('" + Convert.ToString(row[0]) + "','" + Convert.ToString(row[1]) + "','" +....+ Convert.ToString(row[n-1]) + "') 展开
展开全部
DataTable dt = new DataTable("Table1");
dt.Columns.AddRange(new DataColumn[] { new DataColumn("column0"), new DataColumn("column1"), new DataColumn("column2"), new DataColumn("column3") });
for (int j = 0; j < 10; j++)
{
dt.Rows.Add(j, j, j, j);
}
string header = string.Empty;
string query = string.Empty;
header = "insert into [" + dt.TableName + "] (";
foreach (DataColumn item in dt.Columns)
{
header += "[" + item.ColumnName + "],";
}
header = header.Remove(header.Length - 1) + ") values (";
for (int i = 0; i < dt.Rows.Count; i++)
{
string values = string.Empty;
for (int j = 0; j < dt.Columns.Count; j++)
{
values += "'"+dt.Rows[i][j].ToString() + "',";
}
query += header + values.Remove(values.Length - 1) + ")\n";
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
/// <summary>
/// 根据DataTable构建插入语句
/// </summary>
/// <param name="dataTable"></param>
/// <returns></returns>
private string builderSql(DataTable dataTable)
{
StringBuilder sb = new StringBuilder("insert into "+ dataTable.TableName + "(");
StringBuilder head = new StringBuilder();
StringBuilder values = new StringBuilder();
foreach (DataColumn col in dataTable.Columns)
{
head.Append(col.ColumnName + ",");
values.Append("@" + col.ColumnName);
}
head.Remove(head.Length - 1, sb.Length);
values.Remove(values.Length - 1, values.Length);
sb.Append(head).Append(") VALUES (").Append(values).Append(");");
return sb.ToString();
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询