使用 SELECT - C# 获取所有行和列数据

本文关键字:数据 SELECT 获取 使用 | 更新日期: 2023-09-27 18:30:34

我正在尝试从SQL表中获取所有数据,并使用C#编程语言将其存储在列表中。

我正在使用的 SQL 语句是:

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

这与函数在同一个类中使用

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;
  }
}

和这里

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;
  }

我必须以这种方式再创建 9 个函数才能从 Employees 表中获取所有数据。 这似乎效率很低,我想知道是否有更优雅的方法可以做到这一点。

我知道使用适配器是一种方法,但我认为不可能将填充的适配器转换为列表、列表列表等。

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

有什么想法吗?

使用 SELECT - C# 获取所有行和列数据

如果必须以这种方式使用读取器,为什么不创建一个保存表行数据的对象。

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

这样,您就可以按如下方式循环阅读:

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;
    }

您可以使用两个 select 语句来填充两个List<string>,如下面的示例所示,其中读取之间的键是 reader.NextResult();

使用的数据库是标准Microsoft罗斯文数据库。

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;
            }
        }
    }
}

表单代码

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;
            }
        }
    }
}

您始终可以将其全部添加到数据集或数据表中,而不是使用 datareader 循环添加到数组中,数据集允许您以类似于数组的方式访问数据。

        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)
      {}