使用泛型查询数据小例
生活随笔
收集整理的這篇文章主要介紹了
使用泛型查询数据小例
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
在這個例子當中,泛型的出色之處在于,不必為每個類型編寫相同的代碼講閱讀器的數(shù)據(jù)轉(zhuǎn)換為泛型List。
1.GenericMethods類
public class GenericMethods
{
public static List<T> GetListFromCommand<T>(SqlCommand command)
where T : ICreatable, new()
{
List<T> list = new List<T>();
using (command.Connection)
{
command.Connection.Open();
SqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
T t = new T();
t.Create(dr);
list.Add(t);
}
}
return list;
}
}
2.Movie實體類
public class Movie : ICreatable
{
public int ID { get; set; }
public string Name { get; set; }
public void Create(SqlDataReader dr)
{
ID = int.Parse(dr["ID"].ToString());
Name = dr["Name"].ToString();
}
}
3.ICreatable接口
public interface ICreatable
{
void Create(SqlDataReader dr);
}
4.頁面方法調(diào)用
string constring = WebConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
SqlCommand command = new SqlCommand("SELECT * FROM Movies", conn);
List<Movie> list = GenericMethods.GetListFromCommand<Movie>(command);
轉(zhuǎn)載于:https://www.cnblogs.com/Scarface/archive/2011/05/09/2040755.html
《新程序員》:云原生和全面數(shù)字化實踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的使用泛型查询数据小例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 抽象SQL查询:SQL-MAP技术的使用
- 下一篇: c语言复习笔记(2)--标准库中的I/O