简体   繁体   中英

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. It has been discussed in other Stack Overflow questions as well.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM