Bri*_*ton 3 c# sql return selectall
我正在尝试使用 C# 编程语言从 SQL 表中获取所有数据并将其存储在列表中。
我使用的SQL语句是:
private string cmdShowEmployees = "SELECT * FROM Employees;";
Run Code Online (Sandbox Code Playgroud)
这与函数在同一个类中使用
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;
}
}
Run Code Online (Sandbox Code Playgroud)
和这里
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;
}
Run Code Online (Sandbox Code Playgroud)
我必须以这种方式再创建 9 个函数才能从Employees 表中获取所有数据。这看起来效率很低,我想知道是否有更优雅的方法来做到这一点。
我知道使用适配器是一种方法,但我认为不可能将填充的适配器转换为列表、列表列表等。
SqlDataAdapter adapter = sqlDataCollection.getAdapter();
DataSet dataset = new DataSet();
adapter.Fill(dataset, "idEmployees");
dataGridView1.DataSource = dataset;
dataGridView1.DataMember = "idEmployees";
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
小智 6
如果必须以这种方式使用读取器,为什么不创建一个保存表行数据的对象。
public class SomeComplexItem
{
public string SomeColumnValue { get; set;}
public string SomeColumnValue2 { get; set;}
public string SomeColumnValue3 { get; set;}
public string SomeColumnValue4 { get; set;}
}
Run Code Online (Sandbox Code Playgroud)
这样您就可以按如下方式与读者循环浏览:
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34915 次 |
| 最近记录: |