您可以返回IEnumerable,而不是返回Datareader或将所有记录复制到整个返回的内存中DataTable,而PLACEHOLDER_FOR_CODE_2是DataReader记录实现的基本接口。
所以这应该工作,因为yield导致Connection保持活着:
public IEnumerable CreateQuery(string queryString, string connectionString)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand command = new MySqlCommand(queryString, connection))
{
command.Connection.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
yield return (IDataRecord)reader;
}
}
}
}
}例如,如果您想要只获取前5条记录:
var records = CreateQuery("SELECT * FROM ais.country;", Properties.Settings.Default.MySQL).Take(5);
foreach (IDataRecord rec in records)
{
String country = rec.GetString(rec.GetOrdinal("Name"));
}