简体   繁体   中英

get all row and column data using SELECT - C#

I'm trying to get all data from an SQL table and store it in a List using the C# programming language.

the SQL statement I'm using is:

private string cmdShowEmployees = "SELECT * FROM Employees;";

This is being used in the same class as a function

public List<string> showAllIdData()
{
  List<string> id = new List<string>();
  using (sqlConnection = getSqlConnection())
  {
    sqlCommand.Connection = sqlConnection;
    sqlCommand.CommandText = cmdShowEmployees;
    SqlDataReader reader = sqlCommand.ExecuteReader();
    while (reader.Read()) {
      id.Add(reader[0].ToString());
    }
    return id;
  }
}

and here

public List<string> showAllActiveData()
{
  List<string> active = new List<string>();
  using (sqlConnection = getSqlConnection())
  {
    sqlCommand.Connection = sqlConnection;
    sqlCommand.CommandText = cmdShowEmployees;
    SqlDataReader reader = sqlCommand.ExecuteReader();
    while (reader.Read()) {
      active.Add(reader[1].ToString());
    }
    return active;
  }

I would have to create 9 more functions this way in order to get all the data out of the Employees table. This seems very inefficient and I was wondering if there was a more elegant way to do this.

I know using an adapter is one way to do it but I don't think it is possible to convert a filled adapter to a list, list list etc.

SqlDataAdapter adapter = sqlDataCollection.getAdapter();
DataSet dataset = new DataSet();
adapter.Fill(dataset, "idEmployees");
dataGridView1.DataSource = dataset;
dataGridView1.DataMember = "idEmployees";

Any ideas?

If you must use the reader in this way, why not create an object which holds the table row data.

public class SomeComplexItem
{
    public string SomeColumnValue { get; set;}
    public string SomeColumnValue2 { get; set;}
    public string SomeColumnValue3 { get; set;}
    public string SomeColumnValue4 { get; set;}
}

That way you can loop through with your reader as follows:

public List<SomeComplexItem> showAllActiveData()
{
    List<SomeComplexItem> active = new List<SomeComplexItem>();
    using (sqlConnection = getSqlConnection())
    {
        sqlCommand.Connection = sqlConnection;
        sqlCommand.CommandText = cmdShowEmployees;
        SqlDataReader reader = sqlCommand.ExecuteReader();
        while (reader.Read())
        {
            var someComplexItem = new SomeComplexItem();
            someComplexItem.SomeColumnValue = reader[1].ToString();
            someComplexItem.SomeColumnValue2 = reader[2].ToString();
            someComplexItem.SomeColumnValue3 = reader[3].ToString();

            active.Add(someComplexItem);
        }
        return active;

    }

You could use two select statements to populate two List<string> as shown in the example below where the key between reads is reader.NextResult(); .

The database used is the standard Microsoft NorthWind database.

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;

namespace SQL_Server_TwoList
{
    public class DataOperations
    {
        public List<string> Titles { get; set; }
        public List<string> Names { get; set; }

        /// <summary>
        /// Trigger code to load two list above
        /// </summary>
        public DataOperations()
        {
            Titles = new List<string>();
            Names = new List<string>();
        }
        public bool LoadData()
        {
            try
            {
                using (SqlConnection cn = new SqlConnection(Properties.Settings.Default.ConnectionString))
                {
                    string commandText = @"
                    SELECT [TitleOfCourtesy] + ' ' + [LastName] + ' ' + [FirstName] As FullName FROM [NORTHWND.MDF].[dbo].[Employees]; 
                    SELECT DISTINCT [Title] FROM [NORTHWND.MDF].[dbo].[Employees];";

                    using (SqlCommand cmd = new SqlCommand(commandText, cn))
                    {

                        cn.Open();

                        SqlDataReader reader = cmd.ExecuteReader();

                        // get results into first list from first select
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                Names.Add(reader.GetString(0));
                            }

                            // move on to second select
                            reader.NextResult();

                            // get results into first list from first select
                            if (reader.HasRows)
                            {
                                while (reader.Read())
                                {
                                    Titles.Add(reader.GetString(0));
                                }
                            }
                        }
                    }
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}

Form code

namespace SQL_Server_TwoList
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DataOperations dataOps = new DataOperations();
            if (dataOps.LoadData())
            {
                listBox1.DataSource = dataOps.Names;
                listBox2.DataSource = dataOps.Titles;
            }
        }
    }
}

You could always add it all to a dataset or datatable instead of looping through using datareader to add to an array, dataset allows you to access data in similar way to array anyway.

        Connstr = "Data Source = " + SelectedIP + "; Initial Catalog = " + dbName + "; User ID = " + txtUsername.Text +"; Password = "+ txtPassword.Text +"";
        conn = new SqlConnection(Connstr);
        try
        {
            string contents = "SELECT * FROM ..."
            conn.Open();
            SqlDataAdapter da_1 = new SqlDataAdapter(contents, conn);   //create command using contents of sql file
            da_1.SelectCommand.CommandTimeout = 120; //set timeout in seconds

            DataSet ds_1 = new DataSet(); //create dataset to hold any errors that are rturned from the database

            try
            {
                //manipulate database
                da_1.Fill(ds_1);

                if (ds_1.Tables[0].Rows.Count > 0) //loop through all rows of dataset
                {
                   for (int i = 0; i < ds_1.Tables[0].Rows.Count; i++)
                    {
                                            //rows[rownumber][column number/ "columnName"]
                        Console.Write(ds_1.Tables[0].Rows[i][0].ToString() + " ");
                    }
                }
             }
             catch(Exception err)
             {}
         conn.Close();
      }
      catch(Exception ex)
      {}

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