Example #1
0
        public DBAccess(DataBaseType dbType,string connectionString)
        {
            this._dbType = dbType;
            this._connectionString = connectionString;

            this.dbAccess= new DataBaseAccess(this._dbType, this._connectionString);
        }
Example #2
0
        public static void Test()
        {
            DataBaseAccess access=new DataBaseAccess(DataBaseType.SQLite,"Data source=$ROOT$/db.db");
            IList<DataExtendAttr> list=null;

            print:
            access.ExecuteReader("SELECT extID as extendID,* FROM  cms_dataExtendAttr",
                                                            rd=>{
                                 	if(rd.HasRows)
                                 	{
                                 		list=rd.ToEntityList<DataExtendAttr>();
                                 	}
                                                            }
                                );

            foreach(DataExtendAttr a in list)
            {
                Console.WriteLine("{0}-{1}-{2}-{3}",a.ExtendID,a.AttrName,a.AttrType,a.AttrVal);
            }

            Console.WriteLine("----------------------");

             list= access.GetDataSet("SELECT extID as extendID,* FROM  cms_dataExtendAttr").Tables[0].ToEntityList<DataExtendAttr>();

            foreach(DataExtendAttr a in list)
            {
                Console.WriteLine("{0}-{1}-{2}-{3}",a.ExtendID,a.AttrName,a.AttrType,a.AttrVal);
            }

            Console.WriteLine("----------------------");
            System.Threading.Thread.Sleep(1000);
            //goto print;
        }
 /// <summary>
 /// 获取科研成果列表
 /// </summary>
 /// <returns></returns>
 public static DataTable GetIndexProductListDAL()
 {
     string sql = SqlStrClass.SelectIndexListFromProducttb();
     DataBaseAccess dba = new DataBaseAccess();
     DataTable dt = dba.RunSQLStringWithSQLDataTable(sql);
     return dt;
 }
Example #4
0
		public Email(IDataBaseAccess db, ILogger logger, string redirectionEmail, string redirectionDomain, bool isProduction)
		{
			_db = (DataBaseAccess)db;
			_logger = logger;
			_redirectionEmail = redirectionEmail;
			_redirectionDomain = redirectionDomain;
			_isProduction = isProduction;
		}
Example #5
0
		public Email(IDataBaseAccess db)
		{
			_logger = UnityResolver.UnityContainer.Resolve<ILogger>();
			_db = (DataBaseAccess)db;
			_redirectionEmail = Config.Dictionaries.AppSettings.RedirectionEmail;
			_redirectionDomain = Config.Dictionaries.AppSettings.RedirectionDomain;
			bool.TryParse(Config.Dictionaries.AppSettings.Production, out _isProduction);
		}
 private void bindGrid()
 {
     string connString = "Data Source=localhost;Initial Catalog=webinf;Integrated Security=SSPI;";
     DataBaseAccess dbs = new DataBaseAccess(connString);
     String Sqlstring = "select * from Staff";
     //string Sqlstring2 = "select * from Customers";
     DataTable myds = dbs.GetDataTable(Sqlstring);
     //DataSet myds1 = dbs.GetDataSet(Sqlstring2);
     GridView1.DataSource = myds;
     GridView1.DataBind();
     //GridView2.DataSource = myds1;
     //GridView2.DataBind();
 }
Example #7
0
        public IActionResult Security()
        {
            SecurityViewModel model = new SecurityViewModel();
            string            id    = getID();

            if (id == null)
            {
                return(Redirect("/Login/Login"));
            }
            Account account = DataBaseAccess.getObject <Account>(new Account(id));

            model.password = account.password;
            return(View(model));
        }
Example #8
0
        public ActionResult ShowUsers()
        {
            User          obj  = new User();
            SelectReturn  sr   = DataBaseAccess.GetAllTInfo(obj);
            List <object> list = sr.list;

            JsonSerializer jsonlist = new JsonSerializer();
            StringWriter   sw       = new StringWriter();

            jsonlist.Serialize(new JsonTextWriter(sw), list);
            string result = sw.GetStringBuilder().ToString();             //list转化为JSON

            return(Content(result));
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            var registerNumber = Request.QueryString["id"].ToString();
            var email          = Request.QueryString["email"].ToString();

            var regNumb = Encryption.DecryptString(registerNumber);

            var success = DataBaseAccess.ConfirmRegistration(email, regNumb);

            if (!success)
            {
                divModalNoSuccess.Visible = true;
            }
        }
Example #10
0
        private void Update()
        {
            MySqlConnection openConnection =
                DataBaseAccess.getOpenMySqlConnection();
            MySqlCommand commandSql = openConnection.CreateCommand();

            commandSql.CommandText = _updateSql;
            commandSql.Parameters.Add(new MySqlParameter("?codeDeclaration", CodeDeclaration));
            commandSql.Parameters.Add(new MySqlParameter("?traite", Traite));

            commandSql.Prepare();
            commandSql.ExecuteNonQuery();
            openConnection.Close();
        }
Example #11
0
        private DataTable GetQueryView(string queryName, Hashtable hash, int pageSize, int currentPageIndex,
                                       out int totalCount)
        {
            DataBaseAccess db = ExportManager.GetDao();

            ExportItemConfig item       = ExportManager.GetConfigByQueryName(queryName);
            string           query      = item.Query;
            string           queryTotal = item.Total;

            //添加分页参数
            if (hash != null)
            {
                foreach (DictionaryEntry o in hash)
                {
                    if (UnsafeSqlReg.IsMatch(o.Value.ToString()))
                    {
                        throw new ArgumentException("含有不安全的查询!");
                    }
                }
                hash.Add("page_start", currentPageIndex <= 0 ? 0 : (currentPageIndex - 1) * pageSize);
                hash.Add("page_end", (currentPageIndex) * pageSize);
                hash.Add("page_size", pageSize);


                //格式化
                query = query.Template(hash);
                // throw new Exception(query + "/" + currentPageIndex+"/"+pageSize);
                if (!String.IsNullOrEmpty(queryTotal))
                {
                    queryTotal = queryTotal.Template(hash);
                }
            }


            //获取分页结果
            DataTable dataTable = db.GetDataSet(query, hash).Tables[0];

            //获取统计数据
            if (!String.IsNullOrEmpty(queryTotal))
            {
                object data = db.ExecuteScalar(queryTotal, hash);
                int.TryParse(data.ToString(), out totalCount);
            }
            else
            {
                totalCount = dataTable.Rows.Count;
            }

            return(dataTable);
        }
Example #12
0
        protected void Unnamed1_Click(object sender, EventArgs e)
        {
            var user = (User)Session["user"];

            var list = DataBaseAccess.GetUserCartLogin(user.Id);

            if (user.Role == "Customer")
            {
                var responsecustomer = DataBaseAccess.FinishSell(user.Id);

                if (responsecustomer)
                {
                    var email = EmailService.SendFinishSellEmail(user.Email);

                    if (email)
                    {
                        foreach (var item in list)
                        {
                            DataBaseAccess.AddSells(item.Description, user.Email);
                            GetLogedInCart(user.Id);
                        }
                        divModal2.Visible = Visible;
                    }
                }
            }

            if (user.Role == "Resseler" && user.IsResseler == true)
            {
                var response = DataBaseAccess.FinishSell(user.Id);

                if (response)
                {
                    var email = EmailService.SendFinishSellEmail(user.Email);

                    if (email)
                    {
                        foreach (var item in list)
                        {
                            DataBaseAccess.AddSells(item.Description, user.Email);
                            GetLogedInCart(user.Id);
                        }
                        divModal2.Visible = Visible;
                    }
                }
            }
            else
            {
                divModal3.Visible = true;
            }
        }
Example #13
0
 private static void CheckAndInit()
 {
     if (!_inited)
     {
         DataBaseAccess _db = CmsDataBase.Instance;
         if (_db == null)
         {
             throw new ArgumentNullException("_db");
         }
         DbFact = _db.GetAdapter();
         //SQLPack对象
         _inited = true;
     }
 }
Example #14
0
        public ActionResult addCart(string i_id)
        {
            string u_id = getIDFromCookie();

            if (u_id == null)
            {
                return(Redirect("/Login/Login"));
            }
            if (!DataBaseAccess.insertObj(new ShoppingCart(u_id, i_id)))
            {
                HttpContext.Response.StatusCode = 400;
            }
            return(null);
        }
Example #15
0
        private void Insert()
        {
            MySqlConnection openConnection = DataBaseAccess.getOpenMySqlConnection();
            MySqlCommand    commandSql     = openConnection.CreateCommand();

            commandSql.CommandText = _insertSql;

            commandSql.Parameters.Add(new MySqlParameter("?libelleProbleme ", LibelleProbleme));

            commandSql.Prepare();
            commandSql.ExecuteNonQuery();
            CodeProbleme = Convert.ToInt16(commandSql.LastInsertedId);
            openConnection.Close();
        }
Example #16
0
        private void Update()
        {
            MySqlConnection openConnection =
                DataBaseAccess.getOpenMySqlConnection();
            MySqlCommand commandSql = openConnection.CreateCommand();

            commandSql.CommandText = _updateSql;
            commandSql.Parameters.Add(new MySqlParameter("?codeProbleme ", CodeProbleme));
            commandSql.Parameters.Add(new MySqlParameter("?libelleProbleme ", LibelleProbleme));

            commandSql.Prepare();
            commandSql.ExecuteNonQuery();
            openConnection.Close();
        }
Example #17
0
        private void Update()
        {
            MySqlConnection openConnection =
                DataBaseAccess.getOpenMySqlConnection();
            MySqlCommand commandSql = openConnection.CreateCommand();

            commandSql.CommandText = _updateSql;
            commandSql.Parameters.Add(new MySqlParameter("?numContainer ", NumContainer));
            commandSql.Parameters.Add(new MySqlParameter("?dateDerniereInsp ", DateDerniereInsp));

            commandSql.Prepare();
            commandSql.ExecuteNonQuery();
            openConnection.Close();
        }
        public ActionResult ReturnToShowLuggages()
        {
            string cur_state = Request.Params["s"];

            cur_state = cur_state.Trim();

            if (cur_state == "已登机")
            {
                MessageBox.Show("该行李已经登机啦!");
            }
            else
            {
                int    Luggage_ID = int.Parse(Request.Params["l_id"]);
                string Flight_ID  = Request.Params["ff_id"];
                Flight_ID = Flight_ID.Trim();
                int           w = int.Parse(Request.Params["w"]);
                StringBuilder s = new StringBuilder();
                s.Append("已登机");

                LUGGAGE objlug = new LUGGAGE()
                {
                    F_ID = Flight_ID, L_ID = Luggage_ID, WEGHT = Convert.ToInt16(w), STATE = s.ToString()
                };
                db.Updateable(objlug).ExecuteCommand();
            }
            List <Luggage> Luggages = new List <Luggage>();
            List <object>  list     = new List <object>(); //对象
            List <string>  value    = new List <string>(); //值
            Luggage        obj      = new Luggage();
            SelectReturn   sr       = DataBaseAccess.GetAllTInfo(obj);

            list  = sr.list;
            value = sr.value;
            //obj转Luggage
            int flag = 0;

            foreach (object j in list)
            {
                Luggage luggage = new Luggage();//current
                //手动赋值,暂时没有找到映射的方法
                luggage.F_ID  = value[flag++];
                luggage.L_ID  = int.Parse(value[flag++]);
                luggage.Weght = int.Parse(value[flag++]);
                luggage.State = value[flag++];
                Luggages.Add(luggage);
            }
            //
            return(View("ShowLuggages", Luggages));
        }
        // GET: Pedidos/Create
        public ActionResult Create()
        {
            List <ClienteModel> lstClientes = new List <ClienteModel>();
            List <ProdutoModel> lstProdutos = new List <ProdutoModel>();
            SqlConnection       conexao     = DataBaseAccess.ConexaoDB();
            SqlCommand          scpClientes = new SqlCommand(@"SELECT * FROM clientes;", conexao);
            SqlCommand          scpProdutos = new SqlCommand(@"SELECT * FROM produtos;", conexao);

            try
            {
                conexao.Open();
                SqlDataReader sdrClientes = scpClientes.ExecuteReader();
                if (sdrClientes.HasRows)
                {
                    while (sdrClientes.Read())
                    {
                        lstClientes.Add(new ClienteModel {
                            IdCliente = sdrClientes.GetInt32(0), NomeCliente = sdrClientes.GetString(1)
                        });
                    }
                }
                sdrClientes.Dispose();

                SqlDataReader sdrProdutos = scpProdutos.ExecuteReader();
                if (sdrProdutos.HasRows)
                {
                    while (sdrProdutos.Read())
                    {
                        lstProdutos.Add(new ProdutoModel {
                            IdProduto = sdrProdutos.GetInt32(0), DesProduto = sdrProdutos.GetString(1)
                        });
                    }
                }
                scpProdutos.Dispose();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                conexao.Dispose();
                conexao.Close();
            }

            ViewBag.Clientes = new SelectList(lstClientes, "IdCliente", "NomeCliente");
            ViewBag.Produtos = new SelectList(lstProdutos, "IdProduto", "DesProduto");
            return(View());
        }
Example #20
0
        /*
         * 7.12 0:50
         */
        public static string createOrderByShop(string u_id, string receive, List <string> LItemid, List <int> LAmount)
        {
            var DItem = SearchManager.searchItemByShop(LItemid);
            Dictionary <string, int> amount = new Dictionary <string, int>();

            for (int i = 0; i < LItemid.Count() && i < LAmount.Count(); ++i)
            {
                amount[LItemid[i]] = LAmount[i];
            }
            int count = 0;

            foreach (var pair in DItem)
            {
                ++count;
                string ID = getID();
                if (DataBaseAccess.insertObj(new Order(ID, u_id, 0, receive, DateTime.Now, (int)Order.orderVisibility.yes)))
                {
                    bool   res   = true;
                    double total = 0;
                    for (int i = 0; i < pair.Value.Count(); ++i)
                    {
                        res    = res && DataBaseAccess.insertObj(new OrderItem(ID, pair.Value[i].itemID, amount[pair.Value[i].itemID]));
                        total += amount[pair.Value[i].itemID] * pair.Value[i].itemPrice;
                    }
                    if (!res)
                    {
                        --count;
                        int time = 3;
                        while (!DataBaseAccess.deleteObj(new Order(ID, u_id, 0, receive, DateTime.Now, (int)Order.orderVisibility.yes)) && time > 0)
                        {
                            --time;
                        }
                        time = 3;
                        while (!addBalance(u_id, total) & time > 0)
                        {
                            --time;
                        }
                    }
                }
            }
            if (count == DItem.Count())
            {
                return("创建成功");
            }
            else
            {
                return($"部分订单创建失败,仅成功{count}个订单");
            }
        }
Example #21
0
        public IActionResult Registe(string name, string gender, string email, string password, string phone, string nickname)
        {
            User    u = new User(email, name, nickname, gender, Entity.User.normal, 0, "system");
            Account a = new Account(email, password, DateTime.Now, DateTime.Now, "0.0.0.0");

            if (DataBaseAccess.insertObj(u) && DataBaseAccess.insertObj(a))
            {
                return(Login(email, password));
            }
            else
            {
                ModelState.AddModelError("Error", "SignUp Failed!");
                return(View());
            }
        }
Example #22
0
        public IActionResult NewShop()
        {
            string id = getID();

            if (id == null)
            {
                return(Redirect("/Login/Login"));
            }
            NewShopViewModel model = new NewShopViewModel();
            User             user  = DataBaseAccess.getObject <User>(new User(id));

            model.name  = user.userName;
            model.email = user.userId;
            return(View(model));
        }
Example #23
0
        public void RemoveItem(long id)
        {
            int WaitingRemoveIndex = 0;

            for (WaitingRemoveIndex = 0; WaitingRemoveIndex < Collection.Count; WaitingRemoveIndex++)
            {
                if (Collection[WaitingRemoveIndex].ID == id)
                {
                    Collection.RemoveAt(WaitingRemoveIndex);
                    break;
                }
            }
            DataBaseAccess.RemoveItemInDB(id);
            TileService.UpdatePrimaryTile();
        }
Example #24
0
        private void Insert()
        {
            MySqlConnection openConnection = DataBaseAccess.getOpenMySqlConnection();
            MySqlCommand    commandSql     = openConnection.CreateCommand();

            commandSql.CommandText = _insertSql;

            commandSql.Parameters.Add(new MySqlParameter("?dateAchat ", DateAchat));
            commandSql.Parameters.Add(new MySqlParameter("?typeContainer ", TypeContaier));
            commandSql.Parameters.Add(new MySqlParameter("?dateDerniereInsp  ", DateDerniereInsp));
            commandSql.Prepare();
            commandSql.ExecuteNonQuery();
            NumContainer = Convert.ToInt16(commandSql.LastInsertedId);
            openConnection.Close();
        }
        public override void Initialize(ScheduleCreationInfo scheduleCreationInfo)
        {
            base.Initialize(scheduleCreationInfo);
            _activeStaffMembers = scheduleCreationInfo.ActiveStaffMembers.ToObservableCollection();
            _activeCabins       = scheduleCreationInfo.ActiveCabins.ToObservableCollection();

            _activeCabins.Insert(0, Cabin.None);

            _activeWorkAreas = DataBaseAccess.GetWorkAreas().ToObservableCollection();
            _activeWorkAreas.Insert(0, Location.None);

            RaisePropertyChanged(nameof(ActiveStaffMembers));
            RaisePropertyChanged(nameof(ActiveCabins));
            RaisePropertyChanged(nameof(ActiveWorkAreas));
        }
Example #26
0
        public void TestArchiveUpdate()
        {
            DataBaseAccess db  = this._base.GetDb();
            int            aid = 94;
            int            sid = 1;

            int cid = this.GetCid(db, aid, sid);

            new Thread(() =>
            {
                Update(db, aid, cid, "测试标题", "", "", "", "", "", "", "{st:'0',sc:'0',v:'1',p:'0'}", "", "", 75);
            }).Start();
            Update(db, aid, cid, "测试标题", "", "", "", "", "", "", "{st:'0',sc:'0',v:'1',p:'0'}", "", "", 75);
            Thread.Sleep(2000);
        }
        private void GetInactiveResselers()
        {
            Repeater1.DataSource = DataBaseAccess.GetInactiveResselers();
            Repeater1.DataBind();

            if (Repeater1.Items.Count == 0)
            {
                InactiveRlabel.Visible = true;
                activeRlabel.Visible   = false;
            }
            else
            {
                InactiveR.Visible = true;
                activeR.Visible   = false;
            }
        }
Example #28
0
 public void UpdateItem(long id, string newTitle, string newDescription, DateTimeOffset newDueDate, string newImageUrl)
 {
     foreach (var item in Collection)
     {
         if (item.ID == id)
         {
             item.Title       = newTitle;
             item.Description = newDescription;
             item.DueDate     = newDueDate;
             item.ImageUrl    = newImageUrl;
             DataBaseAccess.UpdateItemInDB(id, newTitle, item.IsComplete, newDescription, newDueDate.ToString(), newImageUrl);
             break;
         }
     }
     TileService.UpdatePrimaryTile();
 }
Example #29
0
        public static void saveImage(SearchShop ls)
        {
            var Args = new DynamicParameters();

            saveImage(ls.LSItem);
            ls.imagePath = Image.BasePath + $"/shop/{ls.imageID}.jpg";
            if (File.Exists(ls.imagePath))
            {
                ls.imagePath = $".." + ls.imagePath.Substring(9); return;
            }
            Args.Add($"key", ls.imageID);
            List <Image> lim = DataBaseAccess.Query <Image>($"select * from DBImage where imageID=:key ", Args);

            File.WriteAllBytes(ls.imagePath, lim[0].img);
            ls.imagePath = $".." + ls.imagePath.Substring(9);
        }
Example #30
0
        /// <summary>
        /// 初始化数据库
        /// </summary>
        public static void Initialize(string connectionString, string dataTablePrefix)
        {
            if (String.IsNullOrEmpty(connectionString))
            {
                throw new NullReferenceException("请检查系统是否被授权或使用CmsDataBase.Initialize初始化数据库连接");
            }
            connectionString = connectionString.Replace("$ROOT", String.Intern(AppDomain.CurrentDomain.BaseDirectory));
            DataBaseType   dbType = DataBaseType.MySQL;
            DataBaseAccess db     = DBAccessCreator.GetDbAccess(connectionString, ref dbType);

            _instance             = new DBAccess(dbType, db.DataBaseAdapter.ConnectionString);
            _instance.TablePrefix = dataTablePrefix;

            //测试数据库连接
            testDbConnection(_instance);
        }
        public ActionResult ReceiveMsg()
        {
            //获取当前飞机ID
            string Current_Flight_ID = Request.Params["current_flight"];
            //从这里将座位信息插入 Seating_Chart   座位号
            int Pickrt = int.Parse(Request.Params["result"]);
            //航班ID   Current_Flight_ID
            //顾客ID   从页面传来
            string Current_Customer_ID = Request.Params["Customer_ID"];
            //座位状态,还没有就坐默认为0

            Seat obj = new Seat(Current_Flight_ID, Pickrt, Current_Customer_ID, 0);

            DataBaseAccess.insertObj(obj);
            return(View("ChooseFlight", Flights));
        }
Example #32
0
        public EntityManager(DataBaseAccess db)
        {
            object[] attrs; //datatableAttribtue
            attrs = typeof(Entity).GetCustomAttributes(typeof(DataTableAttribute), true);
            if (attrs.Length == 0)
            {
                throw new DataMappingException("此类未加上DataTable特性!");
            }
            DataTableAttribute tb = attrs[0] as DataTableAttribute;

            tableName = tb.Name;

            properties = typeof(Entity).GetProperties();

            this.db = db;
        }
Example #33
0
 private void UpdateUsuario(Usuario usuario)
 {
     try
     {
         DataBaseAccess.simpleStoredProcedureRequest("pa_usuario_modificar", new SPP[] {
             new SPP("us_id", usuario.Id.ToString()), //0
             new SPP("us_nombre", usuario.Nombre),
             new SPP("us_contra", usuario.Password),
             new SPP("us_email", usuario.Email)
         });
     }
     catch (Exception ex)
     {
         throw new Exception(String.Format("Error: {0}", ex.Message));
     }
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            var list = (List <Product>)Session["tempList"];

            if (!this.IsPostBack)
            {
                var conn = DataBaseAccess.OpenTempData();

                if (list == null)
                {
                    DataBaseAccess.CreateTempTable(conn);

                    Session["conn"] = conn;
                }
            }
        }
Example #35
0
        /// <summary>
        /// 初始化数据库
        /// </summary>
        public static void Initialize(string connectionString, string dataTablePrefix, bool sqlTrace)
        {
            if (String.IsNullOrEmpty(connectionString))
            {
                throw new NullReferenceException("请检查系统是否被授权或使用CmsDataBase.Initialize初始化数据库连接");
            }
            connectionString = connectionString.Replace("$ROOT", FwCtx.PhysicalPath);
            DataBaseType   dbType = DataBaseType.MySQL;
            DataBaseAccess db     = DbAccessCreator.GetDbAccess(connectionString, ref dbType);


            _instance             = new DbAccess(dbType, db.GetDialect().GetConnectionString(), sqlTrace);
            _instance.TablePrefix = dataTablePrefix;
            //测试数据库连接
            testDbConnection(_instance);
        }
Example #36
0
        protected void logInButton_Click(object sender, EventArgs e)
        {
            var email     = userName.Text;
            var pass      = passWd.Text;
            var encryPass = Encryption.EncryptString(pass);

            var user = DataBaseAccess.LoginUser(email, encryPass);



            if (user.Email == null)
            {
                divModal.Visible = true;
                return;
            }
            else if (user.IsActive == 0)
            {
                divModal2.Visible = true;
                return;
            }

            var conn = (SqlConnection)Session["conn"];

            var cartList = DataBaseAccess.GetTempCart(conn);


            if (cartList != null)
            {
                DataBaseAccess.UpdateCart(cartList, user);
            }



            user.IsLogedIn = true;


            Session["user"] = user;

            if (user.Role == "Customer" || user.Role == "Resseler")
            {
                Response.Redirect("IndexLogedin.aspx");
            }
            else if (user.Role == "Admin")
            {
                Response.Redirect("IndexLogedInAdmin.aspx");
            }
        }
Example #37
0
        public string Index()
        {
            DataBaseAccess db = new DataBaseAccess(DataBaseType.MySQL, "server=s3.ns-cache.ops.cc;uid=root;pwd=$Newmin;database=mydb;charset=utf8");
            DataBaseAccess db2 = new DataBaseAccess(DataBaseType.SQLite, String.Format("Data Source={0}/data/#db.db3", AppDomain.CurrentDomain.BaseDirectory));

            int i = 0, j = 0;
            foreach (DataRow dr in db2.GetDataSet("SELECT * FROM O_archives").Tables[0].Rows)
            {
                try
                {
                    
                    db.ExecuteNonQuery("INSERT INTO opsblog_archives(id,cid,`author`,`title`,`properties`,`content`,tags,viewcount,createdate,lastmodifydate) values(@id,@cid,@author,@title,@properties,@content,@tags,@viewcount,createdate,lastmodifydate)",
                        db.NewParameter("@id", dr["id"].ToString()),
                        db.NewParameter("@cid", dr["cid"].ToString()),
                        db.NewParameter("@author", dr["author"].ToString()),
                        db.NewParameter("@title", dr["title"].ToString()),
                        db.NewParameter("@properties", dr["properties"].ToString()),
                        db.NewParameter("@content", dr["content"].ToString()),
                        db.NewParameter("@tags", dr["tags"].ToString()),
                        db.NewParameter("@viewcount", dr["viewcount"].ToString()),
                        db.NewParameter("@createdate", dr["createdate"].ToString()),
                        db.NewParameter("@lastmodifydate", dr["lastmodifydate"].ToString())
                        );
                    
                    ++i;
                }
                catch (Exception ex)
                {
                    ++j;
                }


                /*
                db.ExecuteNonQuery("update  opsblog_archives set createdate=@dt,lastmodifydate=@dt where id=@id",
                    db.dbFactory.CreateParameter("@dt", dr["createdate"]),
                    db.dbFactory.CreateParameter("@id", dr["id"].ToString())
                    );
                */

            }


            //db.ExecuteNonQuery("update  opsblog_archives set source='',outline='',agree=0,disagree=0,isspecial=0,issystem=0,visible=1");

            return string.Format("共导入{0}条,成功{1}条,失败{2}条", (i + j), i, j);
        }
Example #38
0
        public static void ArchiveReCreateDate()
        {
            DataBaseAccess dba=new DataBaseAccess(
                DataBaseType.MySQL,
                "server=s5.ns-cache.ops.cc;database=mydb;uid=newmin;pwd=$Newmin;charset=utf8");
		
		
            IList<int> list= new List<int>();
		
            dba.ExecuteReader("select id from lms_archives where id>524",
                rd=>{
                        while(rd.Read()){
                            list.Add(rd.GetInt32(0));
                        }
                });
		
		
            SqlQuery[] sqls= new SqlQuery[list.Count];
		
            DateTime dt=DateTime.Now;
            int tmpInt=0;
            foreach(int intId in list)
            {
                dt=dt.AddMinutes(-1);
                sqls[tmpInt]=
                    new SqlQuery(
                        "UPDATE lms_archives set lastmodifydate=@dt WHERE id =@id",
                        new object[,]{
                            {"@dt", dt},
                            {"@id",intId}
						
                        });
                tmpInt++;
            }
		
            dba.ExecuteNonQuery(sqls);
        }
Example #39
0
        public static void ReNotIdArchives()
        {
            DataBaseAccess dba=new DataBaseAccess(
                DataBaseType.MySQL,
                "server=s5.ns-cache.ops.cc;database=mydb;uid=newmin;pwd=$Newmin;charset=utf8");
		
		
            IList<int> list= new List<int>();
		
            dba.ExecuteReader("select id from lms_archives where strid=''",
                rd=>{
                        while(rd.Read()){
                            list.Add(rd.GetInt32(0));
                        }
                });
		
		
            foreach(int intId in list)
            {
			
                string strId;
                do
                {
                    strId = IdGenerator.GetNext(5);              //创建5位ID
                } while (
                    int.Parse(dba.ExecuteScalar("SELECT count(1) FROM lms_archives where id='"+strId+"' OR alias='"+strId+"'").ToString())!=0
			
                    );
			
                dba.ExecuteNonQuery("UPDATE lms_archives set strid='"+strId+"' where id="+intId);
			
			
            }
		
            Console.WriteLine("finish!");
        }
 /// <summary>
 /// 获取产品详情
 /// </summary>
 /// <param name="id"></param>
 /// <returns></returns>
 public static DataTable GetProductInfoDAL(int id)
 {
     string sql = SqlStrClass.SelectByIdFromProducttb(id);
     DataBaseAccess dba = new DataBaseAccess();
     return dba.RunSQLStringWithSQLDataTable(sql);
 }
 /// <summary>
 /// 获取菜单列表项
 /// </summary>
 /// <returns></returns>
 public static DataTable GetMenuItemDAL()
 {
     string sql = SqlStrClass.SelectAllFromMenutb();
     DataBaseAccess dba = new DataBaseAccess();
     return dba.RunSQLStringWithSQLDataTable(sql);
 }
Example #42
0
        private bool ExtraDB(string dbType, string connStr,string dbPrefix)
        {
            DataBaseType type=DataBaseType.MySQL;
            switch (dbType)
            {
                case "mysql": type = DataBaseType.MySQL; break;
                case "mssql": type = DataBaseType.SQLServer; break;
                case "sqlite": type = DataBaseType.SQLite; break;
                case "monosqlite": type = DataBaseType.MonoSQLite; break;
                case "oledb": type = DataBaseType.OLEDB; break;
            }

            this.db=new DataBaseAccess(type,connStr.Replace("$ROOT",Cms.PyhicPath));

            string sql=null;
            string sqlScript = null;

            if (type == DataBaseType.MySQL)
            {
                sqlScript=String.Concat(Cms.PyhicPath,MYSQL_INSTALL_SCRIPT);
            }

            //else if (type == DataBaseType.SQLServer)
            //{
            //    sqlScript = String.Concat(Cms.PyhicPath, MSSQL_INSTALL_SCRIPT);
            //}

            if (sqlScript != null)
            {
                //从脚本中读取出SQL语句
                TextReader tr=new StreamReader(sqlScript);

                sql = tr.ReadToEnd().Replace("cms_", dbPrefix)
                    .Replace(",False", ",0")
                    .Replace(",True", ",1")
                    .Replace(",index", ",`index`");
                tr.Dispose();
            }

            if (sql!=null)
            {
                try
                {
                    db.ExecuteScript(sql,null);
                }
                catch(Exception exc)
                {
                    return false;
                }
            }

            return true;
        }
        private bool ExtraDB(string dbType, string connStr, string dbPrefix)
        {
            DataBaseType type = DataBaseType.MySQL;
            switch (dbType)
            {
                case "mysql": type = DataBaseType.MySQL; break;
                case "mssql": type = DataBaseType.SQLServer; break;
                case "sqlite": type = DataBaseType.SQLite; break;
                case "monosqlite": type = DataBaseType.MonoSQLite; break;
                case "oledb": type = DataBaseType.OLEDB; break;
            }

            this.db = new DataBaseAccess(type, connStr.Replace("$ROOT", AtNet.Cms.Cms.PyhicPath));

            string sql = null;
            string sqlScript = null;

            if (type == DataBaseType.MySQL)
            {
                sqlScript = String.Concat(AtNet.Cms.Cms.PyhicPath, MYSQL_INSTALL_SCRIPT);
                return execDbScript(dbPrefix, ref sql, sqlScript);
            }
            return true;
            //else if (type == DataBaseType.SQLServer)
            //{
            //    sqlScript = String.Concat(Cms.PyhicPath, MSSQL_INSTALL_SCRIPT);
            //}
        }