[英]Get all the row data with select statement in codebehind C# using ADO.NET
Maybe someone can help me with the following problem.也许有人可以帮助我解决以下问题。 what i want to achieve is to get all rows of a table and put them in a string with comma between each value.
我想要实现的是获取表的所有行并将它们放入一个字符串中,每个值之间带有逗号。 The result should be a scriptfile to get all of the rowdata in the table.
结果应该是一个脚本文件,用于获取表中的所有行数据。
For so far:到目前为止:
static void Main(string[] args) {
StringBuilder builder = new StringBuilder();
string ConString = @"Data Source=.;Initial Catalog=USR;Integrated Security=True";
foreach (string itemtablename in TableNames())
{
Schema schema = new Schema();
schema.TableName = itemtablename; //the name of the table
//int i = 0;
string queryvalues = "select * from " + itemtablename;
SqlConnection conValues = new SqlConnection(ConString);
using (conValues)
{
conValues.Open();
SqlCommand cmdSchemaValues = new SqlCommand(queryvalues, conValues);
SqlDataReader readerSchemaValues = cmdSchemaValues.ExecuteReader();
DataTable dataTable = readerSchemaValues.GetSchemaTable();
//builder.AppendLine("INSERT INTO " + itemtablename);
//builder.AppendLine(" VALUES (");
for (int i = 0; i < dataTable.Rows.Count; i++)
{
string rowValues= dataTable.Rows[i].ToString() + ",";
builder.Append(rowValues);
}
}
}
System.IO.File.WriteAllText(@"C:\script.txt", builder.ToString());
}
If "generating the insert script for data present in the table" is the objective then you can try using the SQL Server Management Studio to do that.如果目标是“为表中存在的数据生成插入脚本”,那么您可以尝试使用 SQL Server Management Studio 来执行此操作。 It has been discussed in other Stack Overflow questions as well.
它也已在其他Stack Overflow 问题中讨论过。
Try this logic:试试这个逻辑:
foreach(DataRow row in datatable.Rows)
{
builder.AppendLine("INSERT INTO " + itemtablename + "(" + string.Join(", ", datatable.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToArray()).Trim().TrimEnd(","));
builder.AppendLine("VALUES ('" + string.Join("', '", row.ItemArray).Trim().TrimEnd('\'').Trim().TrimEnd(',') + "')")
}
string script = builder.ToString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.