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

新手上路,请多包涵

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

我使用的 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";

有任何想法吗?

原文由 Brian Cotton 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.7k
2 个回答

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

 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;

    }

原文由 KevDev 发布,翻译遵循 CC BY-SA 4.0 许可协议

您始终可以将其全部添加到数据集或数据表中,而不是使用 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)
      {}

原文由 st3_121 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进