private static object sign = new object();

        public static DBHelper CreateMapping(string connStr = "")
        {
            DBHelper db = new DBHelper(connStr);
            return db;
        }

        /// <summary>
        /// 增删改的数据库连接字符串
        /// </summary>
        string conString = "";
        /// <summary>
        /// 查询的数据库连接字符串
        /// </summary>
        string queryConString = "";

        DBHelper(string connStr = "")
        {
            if (string.IsNullOrWhiteSpace(connStr))
            {
                conString = AsString(ConfigurationManager.ConnectionStrings["DBConfig"]);
                if(string.IsNullOrEmpty(conString))WriteErrorLogDataInteraction(conString,"连接字符串获取失败!");
                //第一个链接字符串是ConfigurationManager.ConnectionStrings[0].Name LocalSqlServer不知道是谁,所以要从第二个取
                //如果连接字符串的数量和当前索引+1相同 则从第一个索引开始取
                NameValueCollection connStrs = new NameValueCollection();
                int j = 0;
                for (int i = 0; i < ConfigurationManager.ConnectionStrings.Count; i++)
                {
                    if (ConfigurationManager.ConnectionStrings[i].Name.StartsWith("QueryDB"))
                    {
                        connStrs.Add(j.ToString(), ConfigurationManager.ConnectionStrings[i].ToString());
                        j++;
                    }
                }
                // 加锁
                lock (sign)
                {
                    if (connStrs.Count > 0)
                    {
                        if (connStrs.Count >= ConnIndex)
                        {
                            ConnIndex = 0;
                        }
                        queryConString = connStrs[ConnIndex].ToString();
                        ConnIndex++;
                    }
                    else
                    {
                        queryConString = conString;
                    }
                }
            }
            else
            {
                conString = connStr;
                queryConString = connStr;
            }

            DBMapping = new SqlDatabase(conString);
            QueryDBMapping = new SqlDatabase(queryConString);

        }

DBHelper如果多个进行同时运行时,就会出现错误。所以应该加上锁Lock 。以确保一个线程执行完之后再执行另一个线程。

posted on 2013-05-31 20:42  王洪洪  阅读(1696)  评论(0编辑  收藏  举报