标签:
自己总结的一些东西
这个小程序支持mysql和sqlite数据库,可以根据需求使用不同数据库
演示的Admin类如下,为了简单只有两个字段
1 1 class Admin 2 2 { 3 3 public Admin() { } 4 4 5 5 public Admin(DbDataReader dr) 6 6 { 7 7 this.Id = dr["id"].ToString(); 8 8 this.Password = dr["password"].ToString(); 9 9 } 10 10 11 11 String id; 12 12 13 13 public String Id 14 14 { 15 15 get { return id; } 16 16 set { id = value; } 17 17 } 18 18 String password; 19 19 20 20 public String Password 21 21 { 22 22 get { return password; } 23 23 set { password = value; } 24 24 }
下来是AdminBaseMgr类,这是一个抽象类
1 abstract class AdminBaseMgr 2 { 3 4 public abstract bool insert(Admin admin); 5 public abstract bool delete(Admin admin); 6 public abstract bool delete(String id); 7 public abstract bool update(Admin admin); 8 public abstract Admin getAdminById(Admin admin); 9 public abstract Admin getAdminById(String id); 10 11 }
下来是AdminSqliteMgr类的实现,对应Sqlite数据库
1 class AdminSqliteMgr : AdminBaseMgr 2 { 3 private AdminSqliteMgr() { } 4 5 private static AdminSqliteMgr adminMgr = null; 6 7 public static AdminBaseMgr getAdminMgr() 8 { 9 if (adminMgr != null) 10 { 11 return adminMgr; 12 } 13 else 14 { 15 16 return (adminMgr = new AdminSqliteMgr()); 17 } 18 } 19 public override bool insert(Admin admin) 20 { 21 /* String sql = "insert into admin values (@id,@password)"; 22 SQLiteParameter[] p = { new SQLiteParameter("@id","root"), 23 new SQLiteParameter("@password","root") 24 }; 25 */ 26 String sql = "insert into admin values (‘root‘,‘root‘)"; 27 28 return SqliteHelper.executeNonQuary(sql) == 1; 29 } 30 31 public override bool delete(Admin admin) 32 { 33 return delete(admin.Id); 34 } 35 36 public override bool delete(string id) 37 { 38 String sql = "delete from admin where id=@id"; 39 SQLiteParameter p = new SQLiteParameter("@id",id); 40 return SqliteHelper.executeNonQuary(sql,p)==1; 41 } 42 43 public override bool update(Admin admin) 44 { 45 throw new NotImplementedException(); 46 } 47 48 public override Admin getAdminById(Admin admin) 49 { 50 return getAdminById(admin.Id); 51 } 52 53 public override Admin getAdminById(string id) 54 { 55 String sql = "select * from admin where id=@id"; 56 SQLiteParameter[] p = {new SQLiteParameter("@id",id)}; 57 SQLiteDataReader dr = SqliteHelper.executeReader(sql, p); ; 58 59 return new Admin(dr); 60 } 61 }
Mysql的一样就不上了
再下来就是AdminMgrFactory类,根据不同的数据库返回不同的AdminMgr
1 class AdminMgrFactory 2 { 3 public static AdminBaseMgr getAdminMgr() { 4 switch (SysConfig.DB_TYPE) 5 { 6 case "mysql": 7 return AdminMysqlMgr.getAdminMgr(); 8 9 case "sqlite": 10 return AdminSqliteMgr.getAdminMgr(); 11 } 12 13 return null; 14 }
调用如下
1 static void Main(string[] args) 2 { 3 AdminMgrFactory.getAdminMgr().delete("root"); 4 }
这样只需要该变配置信息就可以使用不同的数据库了
---2015年4月22日23:22:57
标签:
原文地址:http://www.cnblogs.com/ahaobest/p/4449039.html