简体   繁体   中英

How to save all records into an array from the SQL SERVER database table?

I have a table in my database. I want to save all SQL SERVER Database Table records into the array.I searched everywhere all I am getting is to copying data from dataTable to array. Is that possible save all records into the array from the database table? If yes please help me. I would like to get the code in C#.

Edited: I want to process all the rows in the DataTable but going row by row through Datatable is consuming more time. So I am looking for better performance with other features like arrays or structures may be.

Not sure what you are trying but seems pretty expensive and probably not a good idea , we can probably find another approach to deal with your problem and take this one out completely.

However for your question , the answer goes something like this:

    public static void Main(string args[])
    {

        List<object> objectList = new List<object>();
        var commandText = "Select name  from sys.tables";

        SqlConnection sqlConn = null;//Initialize
        SqlCommand command = new SqlCommand(commandText, sqlConn);

        var sqlReader = command.ExecuteReader();

        while (sqlReader.Read())
        {
            commandText = $"Select * from {sqlReader["name"]}";
            command = new SqlCommand(commandText, sqlConn);

            var subReader = command.ExecuteReader();

            while (subReader.Read())
            {
                //Loop through and add to list
                objectList.Add();
            }
        }

    }

You could use EF and load your data like this:

var data = context.YourTable.ToList();

learn about EF

but be aware that if you have a big table it may slow down your application and then you have to do some workarounds like paging. usually you may want to pass some criteria in Where extension method

also you can run a raw SQL query with EF:

context.Database.SqlQuery<YourMappingClass>("SELECT * FROM YourTable")

choosing how to connect to your databse is a matter of preference, I prefer EF you can use ADO.NET.

Using ADO:

    using(SqlConnection conn = new SqlConnection()) 
    {
        conn.ConnectionString = "Server=[server_name];Database=[database_name];Trusted_Connection=true";

    SqlCommand command = new SqlCommand("SELECT * FROM YourTable", conn);
    }
using (SqlDataReader reader = command.ExecuteReader())
{
    var list = new List<YourMappingClass>();
    while (reader.Read())
    {

        var obj = new YourMappingClass();
        obj.Prop1=reader[0];
        obj.Prop2=reader[1];
        list.Add(data);
    }
}

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