标签:style blog io ar color os sp on 数据
我的初衷是这样的:在多线程环境下,每个数据库编号对应一个DbHelper对象。
下面是代码,不知道这样写有什么问题。
1 namespace TestDAL 2 { 3 public class DB 4 { 5 private static string[] ConnString = new[] 6 { 7 "unknown", "Data Source=163.163.1.100;Initial Catalog=xiaomi;User Id=sa;Password=1234567890;", 8 "Data Source=163.163.1.101;Initial Catalog=xiaomi;User Id=sa;Password=1234567890;" 9 }; 10 private static readonly ConcurrentDictionary<int, DbHelperSQLP> concurentDictionary; 11 static DB() 12 { 13 concurentDictionary = new ConcurrentDictionary<int, DbHelperSQLP>(); 14 } 15 private DB() 16 { 17 } 18 public static DbHelperSQLP GetDBHelper(int id) 19 { 20 if (!concurentDictionary.ContainsKey(id)) 21 concurentDictionary.TryAdd(id, new DbHelperSQLP(ConnString[id])); 22 DbHelperSQLP db; 23 bool result = concurentDictionary.TryGetValue(id, out db); 24 return result ? db : null; 25 } 26 } 27 }
调用方法是:
1 /// <summary> 2 /// 得到一个对象实体 3 /// </summary> 4 public xiaomi GetModel(int dbno, int id) 5 { 6 StringBuilder strSql = new StringBuilder(); 7 strSql.Append("select top 1 id,username,password,email,ip from xiaomi "); 8 strSql.Append(" where id=@id"); 9 SqlParameter[] parameters = { 10 new SqlParameter("@id", SqlDbType.Int,4) 11 }; 12 parameters[0].Value = id; 13 DbHelperSQLP helper = DB.GetDBHelper(dbno); 14 if (helper == null) 15 throw new SqlNullValueException("没有找到数据库地址"); 16 DataSet ds = helper.Query(strSql.ToString(), parameters); 17 return ds.Tables[0].Rows.Count > 0 ? DataRowToModel(ds.Tables[0].Rows[0]) : null; 18 }
标签:style blog io ar color os sp on 数据
原文地址:http://www.cnblogs.com/ha666/p/4128365.html