一个关于多线程和DbHelper的问题

时间:2023-01-02 14:49:15

我的初衷是这样的:在多线程环境下,每个数据库编号对应一个DbHelper对象。

下面是代码,不知道这样写有什么问题。

 namespace TestDAL
 {
     public class DB
     {
         private static string[] ConnString = new[]
         {
             "unknown", "Data Source=163.163.1.100;Initial Catalog=xiaomi;User Id=sa;Password=1234567890;",
             "Data Source=163.163.1.101;Initial Catalog=xiaomi;User Id=sa;Password=1234567890;"
         };
         private static readonly ConcurrentDictionary<int, DbHelperSQLP> concurentDictionary;
         static DB()
         {
             concurentDictionary = new ConcurrentDictionary<int, DbHelperSQLP>();
         }
         private DB()
         {
         }
         public static DbHelperSQLP GetDBHelper(int id)
         {
             if (!concurentDictionary.ContainsKey(id))
                 concurentDictionary.TryAdd(id, new DbHelperSQLP(ConnString[id]));
             DbHelperSQLP db;
             bool result = concurentDictionary.TryGetValue(id, out db);
             return result ? db : null;
         }
     }
 }

调用方法是:

         /// <summary>
         /// 得到一个对象实体
         /// </summary>
         public xiaomi GetModel(int dbno, int id)
         {
             StringBuilder strSql = new StringBuilder();
             strSql.Append("select  top 1 id,username,password,email,ip from xiaomi ");
             strSql.Append(" where id=@id");
             SqlParameter[] parameters = {
                     )
             };
             parameters[].Value = id;
             DbHelperSQLP helper = DB.GetDBHelper(dbno);
             if (helper == null)
                 throw new SqlNullValueException("没有找到数据库地址");
             DataSet ds = helper.Query(strSql.ToString(), parameters);
             ].Rows.Count >  ? DataRowToModel(ds.Tables[].Rows[]) : null;
         }