public void ParseAllSqls() { var tt = @"/*use his*/ select * from t1 where time between '{Start}' and '{End}' /*use his_bak*/ delete from t2 where time between '{Start}' and '{End}'; /*use his_bak*/ insert t2; "; var cs = SqlSection.ParseAll(tt); Assert.NotNull(cs); Assert.Equal(3, cs.Length); Assert.Equal("his", cs[0].ConnName); Assert.Equal(SqlActions.Query, cs[0].Action); Assert.Equal("select * from t1 where time between '{Start}' and '{End}'", cs[0].Sql); Assert.Equal("his_bak", cs[1].ConnName); Assert.Equal(SqlActions.Execute, cs[1].Action); Assert.Equal("delete from t2 where time between '{Start}' and '{End}'", cs[1].Sql); Assert.Equal("his_bak", cs[2].ConnName); Assert.Equal(SqlActions.Insert, cs[2].Action); Assert.Equal("insert t2", cs[2].Sql); }
public void ParseQuery() { var tt = @"/*use his*/ select * from t1 where time between '{Start}' and '{End}' "; var section = new SqlSection(); section.Parse(tt); Assert.Equal("his", section.ConnName); Assert.Equal(SqlActions.Query, section.Action); Assert.Equal("select * from t1 where time between '{Start}' and '{End}'", section.Sql); }
public void ParseUpdate() { var tt = @"/*use his*/ update t1 set c1=v1, c2=v2 where id=123; "; var section = new SqlSection(); section.Parse(tt); Assert.Equal("his", section.ConnName); Assert.Equal(SqlActions.Execute, section.Action); Assert.Equal("update t1 set c1=v1, c2=v2 where id=123", section.Sql); }
public void ParseDelete() { var tt = @"/*use his*/ delete from t2 where time between '{Start}' and '{End}'; "; var section = new SqlSection(); section.Parse(tt); Assert.Equal("his", section.ConnName); Assert.Equal(SqlActions.Execute, section.Action); Assert.Equal("delete from t2 where time between '{Start}' and '{End}'", section.Sql); }
public void ParseInsert() { var tt = @"/*use his*/ insert into t1 (c1, c2) values(v1, v2); "; var section = new SqlSection(); section.Parse(tt); Assert.Equal("his", section.ConnName); Assert.Equal(SqlActions.Execute, section.Action); Assert.Equal("insert into t1 (c1, c2) values(v1, v2)", section.Sql); }
protected void ApplicationButton_Click(object sender, EventArgs e) { try { DateTime dt = DateTime.Now; Sqlsectionregistration.InsertParameters["suser_id"].DefaultValue = StudentId.Text; Sqlsectionregistration.InsertParameters["section_id"].DefaultValue = SectionDropDown.SelectedValue; SqlSection.SelectCommand = "Select * from section where section_id= '" + SectionDropDown.SelectedValue + "'"; DataSourceSelectArguments dsArguments = new DataSourceSelectArguments(); DataView dvView = new DataView(); dvView = (DataView)SqlSection.Select(dsArguments); string strcurrentavailability = dvView[0].Row["section_availabilty"].ToString(); int currentavailability = 0; currentavailability = Convert.ToInt32(strcurrentavailability); String index = RegordropRadioButton.SelectedValue; if (currentavailability > 0) { int newcurrentavailability = 0; if (index.Equals("0")) { Sqlsectionregistration.InsertParameters["registration_status"].DefaultValue = "Y"; newcurrentavailability = currentavailability - 1; } else if (index.Equals("1")) { Sqlsectionregistration.InsertParameters["registration_status"].DefaultValue = "N"; newcurrentavailability = currentavailability + 1; } SqlSectionUpdate.UpdateParameters["section_availabilty"].DefaultValue = Convert.ToString(newcurrentavailability); SqlSectionUpdate.UpdateParameters["original_section_id"].DefaultValue = SectionDropDown.SelectedValue; SqlSectionUpdate.UpdateParameters["original_section_availabilty"].DefaultValue = Convert.ToString(currentavailability); SqlSectionUpdate.Update(); RegistrationStatusLabel.Text = "Registered Successfully" + dt.ToString(); } if (currentavailability <= 0) { Sqlsectionregistration.InsertParameters["registration_status"].DefaultValue = "N"; RegistrationStatusLabel.Text = "No Availability"; } Sqlsectionregistration.InsertParameters["registration_date"].DefaultValue = dt.ToString(); Sqlsectionregistration.Insert(); } catch (Exception ex) { throw new ApplicationException("Sorry for the inconvenience", ex); } }
public void ParseBatchInsert() { var tt = @"/*use his_bak*/ insert t2; "; var section = new SqlSection(); section.Parse(tt); Assert.Equal("his_bak", section.ConnName); Assert.Equal(SqlActions.Insert, section.Action); Assert.Equal("insert t2", section.Sql); }
protected void SectionSubmitButton_Click(object sender, EventArgs e) { try { SqlSection.InsertParameters["section_id"].DefaultValue = SectionIDTxt.Text; SqlSection.InsertParameters["course_id"].DefaultValue = selCourse.SelectedValue; SqlSection.InsertParameters["fuser_id"].DefaultValue = selFaculty.SelectedValue; SqlSection.InsertParameters["section_availabilty"].DefaultValue = SectionAvailabilityTxt.Text; SqlSection.InsertParameters["credits"].DefaultValue = CreditsTxt.Text; SqlSection.InsertParameters["semester"].DefaultValue = SemesterTxt.Text; SqlSection.Insert(); msg.Text = "Saved Successfully"; } catch (Exception ex) { throw new ApplicationException("Sorry for the inconvenience", ex); } }
/// <summary>执行</summary> /// <param name="ctx"></param> /// <returns></returns> protected override Int32 Execute(JobContext ctx) { //var sqls = ctx.Task.Data as String; var sqls = Job.Data; sqls = TemplateHelper.Build(sqls, ctx.Task.Start, ctx.Task.End); // 向调度中心返回解析后的Sql语句 ctx.Remark = sqls; var sections = SqlSection.ParseAll(sqls); if (sections.Length == 0) { return(-1); } var rs = ExecuteSql(sections, ctx, (section, dt) => SqlMessage.ProduceMessage(dt, ctx)); return(rs); }
string _userRawSql; //raw sql from user code public SqlStringTemplate(string rawSql) { _userRawSql = rawSql; //------------------------------ //parse int length = rawSql.Length; ParseState state = ParseState.FIND_MARKER; StringBuilder stBuilder = new StringBuilder(); //TODO: review parser state, escape ' or " or ` char binderEscapeChar = '\0'; char escapeChar = '\0'; for (int i = 0; i < length; i++) { char ch = rawSql[i]; switch (state) { default: //unknown state must throw exception, so we can see if something changed throw new NotSupportedException(); case ParseState.FIND_MARKER: if (ch == '?' || ch == '@') { binderEscapeChar = ch; //found begining point of new marker if (stBuilder.Length > 0) { _sqlSections.Add(new SqlSection(stBuilder.ToString(), SqlSectionKind.SqlText)); stBuilder.Length = 0; } state = ParseState.COLLECT_MARKER_KEY; } else if (ch == '\'' || ch == '"' || ch == '`') { escapeChar = ch; state = ParseState.STRING_ESCAPE; } stBuilder.Append(ch); break; case ParseState.COLLECT_MARKER_KEY: if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '_') { stBuilder.Append(ch); } else if (ch == '?') { //this is special marker key stBuilder.Append(ch); if (binderEscapeChar == '?') { state = ParseState.COLLECT_SP_MARKER_KEY; } else { //eg ?@ //error throw new NotSupportedException("syntax err!"); } } else if (ch == '@') { stBuilder.Append(ch); if (binderEscapeChar == '@') { //@@ state = ParseState.FIND_MARKER; //goto normal text state } else { //eg @? //eg ?@ //error throw new NotSupportedException("syntax err!"); } } else { //value binding marking end here if (stBuilder.Length > 0) { var valueSection = new SqlBoundSection(stBuilder.ToString()); _sqlSections.Add(valueSection); _valuesKeys.Add(valueSection); stBuilder.Length = 0; } state = ParseState.FIND_MARKER; stBuilder.Append(ch); } break; case ParseState.COLLECT_SP_MARKER_KEY: if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '_') { stBuilder.Append(ch); } else { //special marker end here if (stBuilder.Length > 0) { var specialSection = new SqlSection(stBuilder.ToString(), SqlSectionKind.SpecialKey); _sqlSections.Add(specialSection); _specialKeys.Add(specialSection); stBuilder.Length = 0; } state = ParseState.FIND_MARKER; stBuilder.Append(ch); } break; case ParseState.STRING_ESCAPE: { if (ch == '\'' || ch == '"' || ch == '`') { if (escapeChar == ch) { escapeChar = '\0'; //go back to find marker state state = ParseState.FIND_MARKER; } } stBuilder.Append(ch); } break; } //end swicth } //end for if (stBuilder.Length > 0) { switch (state) { default: throw new NotSupportedException(); case ParseState.FIND_MARKER: _sqlSections.Add(new SqlSection(stBuilder.ToString(), SqlSectionKind.SqlText)); break; case ParseState.COLLECT_MARKER_KEY: var valueSection = new SqlBoundSection(stBuilder.ToString()); _sqlSections.Add(valueSection); _valuesKeys.Add(valueSection); break; case ParseState.COLLECT_SP_MARKER_KEY: var specialSection = new SqlSection(stBuilder.ToString(), SqlSectionKind.SpecialKey); _sqlSections.Add(specialSection); _specialKeys.Add(specialSection); break; } } }
private IEnumerable <IInsqlSection> ParseSectionDescriptors(XElement root) { var sqlSections = root.Elements(XName.Get("sql", "")).Select(element => { var id = element.Attribute(XName.Get("id", "")); if (id == null || string.IsNullOrWhiteSpace(id.Value)) { throw new Exception("insql sql section element `id` is empty !"); } var section = new SqlSection(id.Value); section.Elements.AddRange(this.ParseSqlSections(element)); return(section); }).Cast <IInsqlSection>(); var selectSqlSections = root.Elements(XName.Get("select", "")).Select(element => { var id = element.Attribute(XName.Get("id", "")); if (id == null || string.IsNullOrWhiteSpace(id.Value)) { throw new Exception("insql select insert sql section element `id` is empty !"); } var section = new SqlSection(id.Value); section.Elements.AddRange(this.ParseSqlSections(element)); return(section); }).Cast <IInsqlSection>(); var insertSqlSections = root.Elements(XName.Get("insert", "")).Select(element => { var id = element.Attribute(XName.Get("id", "")); if (id == null || string.IsNullOrWhiteSpace(id.Value)) { throw new Exception("insql insert sql section element `id` is empty !"); } var section = new SqlSection(id.Value); section.Elements.AddRange(this.ParseSqlSections(element)); return(section); }).Cast <IInsqlSection>(); var updateSqlSections = root.Elements(XName.Get("update", "")).Select(element => { var id = element.Attribute(XName.Get("id", "")); if (id == null || string.IsNullOrWhiteSpace(id.Value)) { throw new Exception("insql update sql section element `id` is empty !"); } var section = new SqlSection(id.Value); section.Elements.AddRange(this.ParseSqlSections(element)); return(section); }).Cast <IInsqlSection>(); var deleteSqlSections = root.Elements(XName.Get("delete", "")).Select(element => { var id = element.Attribute(XName.Get("id", "")); if (id == null || string.IsNullOrWhiteSpace(id.Value)) { throw new Exception("insql delete sql section element `id` is empty !"); } var section = new SqlSection(id.Value); section.Elements.AddRange(this.ParseSqlSections(element)); return(section); }).Cast <IInsqlSection>(); var codeSections = root.Elements(XName.Get("code", "")).Select(element => { var id = element.Attribute(XName.Get("id", "")); if (id == null || string.IsNullOrWhiteSpace(id.Value)) { throw new Exception("insql code section element `id` is empty !"); } return(new CodeSection(id.Value, element.Value)); }).Cast <IInsqlSection>(); return(sqlSections .Concat(selectSqlSections) .Concat(insertSqlSections) .Concat(updateSqlSections) .Concat(deleteSqlSections) .Concat(codeSections).ToList()); }
protected void Edit_Users(object sender, EventArgs e) { if (!CommonManager.Web.CheckPostSource()) { return; } if (UserID == 0) { return; } DataRow row = new BLL.Member().GetInfo(UserID.ToString()); if (row == null) { return; } using (DbTrans trans = DbSession.Default.BeginTrans()) { try { #region 对TUsers表的修改 if (txtNickName.Text.Trim() == "") { CommonManager.Web.RegJs(this, "alert('昵称不能为空!');location.href=location.href;", false); return; } string nickName = txtNickName.Text.Trim(); StringBuilder sql = new StringBuilder("update TUsers set "); sql.Append(" Sex=@Sex,"); sql.Append(" Disabled=@Disabled,"); sql.Append(" NickName=@NickName "); if (!string.IsNullOrEmpty(txtPassWord.Text.Trim())) { sql.Append(" ,Pass=@Password"); } if (!string.IsNullOrEmpty(txtTwoPassWord.Text.Trim())) { sql.Append(" ,TwoPassword=@TwoPassword"); } sql.Append(" where UserID=@UserID;"); SqlSection sect = trans.FromSql(sql.ToString()) .AddInputParameter("@Sex", DbType.Int16, rdolSex.SelectedItem.Value) .AddInputParameter("@Disabled", DbType.Int32, rdolDisabled.SelectedItem.Value) .AddInputParameter("@UserID", DbType.Int32, UserID) .AddInputParameter("@NickName", DbType.Int32, nickName); if (!string.IsNullOrEmpty(txtPassWord.Text.Trim())) { sect.AddInputParameter("@Password", DbType.String, Utility.Common.md5(txtPassWord.Text.Trim()) /*CommonManager.String.EncryptMD5SystemDefaultMethod(txtPassWord.Text.Trim(),false,true)*/); } if (!string.IsNullOrEmpty(txtTwoPassWord.Text.Trim())) { sect.AddInputParameter("@TwoPassword", DbType.String, Utility.Common.md5(txtTwoPassWord.Text.Trim()) /*CommonManager.String.EncryptMD5SystemDefaultMethod( txtTwoPassWord.Text.Trim(), false, true )*/); } sect.Execute(); #endregion #region 判断是否需要修改TMatchTable if (row["Master"].ToString() != ddlMaster.SelectedItem.Value) { sql = new StringBuilder(); if (ddlMaster.SelectedItem.Value == "3") { sql.Append("update TMatchTable set MasterPower=268435455 where UserID=@UserID;"); } else if (ddlMaster.SelectedItem.Value == "0") { sql.Append("update TMatchTable set MasterPower=0 where UserID=@UserID;"); } trans.FromSql(sql.ToString()).AddInputParameter("@UserID", DbType.Int32, UserID).Execute(); } #endregion #region 计算VIP时间 int addvip = (int)row["VipTime"]; //得到原来的时间,秒数 if (rdolVip.SelectedIndex != -1 || (!string.IsNullOrEmpty(txtCustomVIP.Text.Trim()))) { int tmp = 0; if (rdolVip.SelectedIndex != -1) //预设值优先 { tmp = int.Parse(rdolVip.SelectedItem.Value); } else { if (!CommonManager.String.IsInteger(txtCustomVIP.Text.Trim())) { CommonManager.Web.RegJs(this, "alert('自定义天数必须为数字!');location.href=location.href;", false); return; } tmp = (int.Parse(txtCustomVIP.Text.Trim()) * 24 * 3600); } //如果不是取消vip,则补齐时间差 if (tmp > 0) { DateTime curVIP = (DateTime)row["VipTime2"]; //得到原来时间的DateTime格式 if (curVIP == new DateTime(1970, 1, 1, 8, 0, 0)) { //从未设置过vip时间,则用当前时间与初始时间的时间差加上要增加的时间。 addvip = (int)(DateTime.Now - new DateTime(1970, 1, 1, 8, 0, 0)).TotalSeconds + tmp; } else if (curVIP < DateTime.Now) { //有过vip,但已到期,则补齐时间差 addvip += (int)(DateTime.Now - curVIP).TotalSeconds + tmp; } else { //有vip,且未到期,则在原来基础上增加 addvip += tmp; } } else { //取消vip addvip = 0; } } #endregion Int64 mon; Int64 bmon; #region 判断是否需要插入金币修改表 if (!Int64.TryParse(txtWalletMoney.Text.Trim(), out mon)) { CommonManager.Web.RegJs(this, "alert('钱包金币数必须为数字,或超出整数范围');location.href=location.href;", false); return; } if (!Int64.TryParse(txtBankMoney.Text.Trim(), out bmon)) { CommonManager.Web.RegJs(this, "alert('银行金币数必须为数字,或超出整数范围');location.href=location.href;", false); return; } if (!CommonManager.String.IsInteger(txtFascination.Text.Trim())) { CommonManager.Web.RegJs(this, "alert('魅力数必须为数字!');location.href=location.href;", false); return; } string newWM = string.IsNullOrEmpty(txtWalletMoney.Text.Trim()) ? "0" : txtWalletMoney.Text.Trim(); string newBM = string.IsNullOrEmpty(txtBankMoney.Text.Trim()) ? "0" : txtBankMoney.Text.Trim(); #region Old code /* * if( row["WalletMoney"].ToString() != newWM ) * { * sql = new StringBuilder(); * sql.Append( "insert into Web_MoneyChangeLog (userid,username,frontmoney,aftermoney,changetype,addtime,adduser)" ); * sql.Append( " values (@UserID,@UserName,@OldWalletMoney,@WalletMoney,0,getdate(),@AdminName);" ); * * trans.FromSql( sql.ToString() ) * .AddInputParameter( "@UserID", DbType.Int32, UserID ) * .AddInputParameter( "@UserName", DbType.String, row["UserName"].ToString() ) * .AddInputParameter("@OldWalletMoney", DbType.Int32, row["WalletMoney"]) * .AddInputParameter("@WalletMoney", DbType.Int32, newWM) * .AddInputParameter( "@AdminName", DbType.Int16, AdminInfo["UserName"].ToString() ) * .Execute(); * //int dvalue = int.Parse( newWM ) - (int)row["WalletMoney"]; * //if( dvalue > 0 ) * //{ * // MoneyOperator.Default.Add_Web_Record_MoneyIncrease( dvalue, Session["AdminName"].ToString() + "管理员手动给玩家" + row["UserName"].ToString() + "添加钱包金币" ); * //} * //else * //{ * // MoneyOperator.Default.Add_Web_Record_MoneyDecrease( Math.Abs( dvalue ), Session["AdminName"].ToString() + "管理员手动减去玩家" + row["UserName"].ToString() + "钱包金币" ); * //} * } * if( row["BankMoney"].ToString() != newBM ) * { * sql = new StringBuilder(); * sql.Append( "insert into Web_MoneyChangeLog (userid,username,frontmoney,aftermoney,changetype,addtime,adduser)" ); * sql.Append( " values (@UserID,@UserName,@OldBankMoney,@BankMoney,0,getdate(),@AdminName);" ); * * trans.FromSql( sql.ToString() ) * .AddInputParameter( "@UserID", DbType.Int32, UserID ) * .AddInputParameter( "@UserName", DbType.String, row["UserName"].ToString() ) * .AddInputParameter("@OldBankMoney", DbType.Int32, row["WalletMoney"]) * .AddInputParameter("@BankMoney", DbType.Int32, newBM) * .AddInputParameter( "@AdminName", DbType.Int16, AdminInfo["UserName"].ToString() ) * .Execute(); * * //int dvalue = int.Parse( newBM ) - (int)row["BankMoney"]; * //if( dvalue > 0 ) * //{ * // MoneyOperator.Default.Add_Web_Record_MoneyIncrease( dvalue, Session["AdminName"].ToString() + "管理员手动给玩家" + row["UserName"].ToString() + "添加银行金币" ); * //} * //else * //{ * // MoneyOperator.Default.Add_Web_Record_MoneyDecrease( Math.Abs( dvalue ), Session["AdminName"].ToString() + "管理员手动减去玩家" + row["UserName"].ToString() + "银行金币" ); * //} * * } */ #endregion if (row["WalletMoney"].ToString() != newWM || row["BankMoney"].ToString() != newBM) //如果修改金币,则插入金币变化日志 { Int64 startMoney = Convert.ToInt64(row["WalletMoney"]) + Convert.ToInt64(row["BankMoney"]); Int64 changeMoney = (Convert.ToInt64(newWM) + Convert.ToInt64(newBM)) - startMoney; string remark = ChineseMessage.adminManageNameMessage + AdminUserName + " " + ChineseMessage.adminManageIdMessage + AdminUserID; BLL.Member.WriteMoneyExChangeLog(UserID.ToString(), startMoney, changeMoney, (int)Library.MoneyChangeType.管理员修改金币, remark); } #endregion #region 对TUserInfo表的修改 sql = new StringBuilder(); sql.Append("update TUserInfo set "); sql.Append(" Member=@Member,"); sql.Append(" Master=@Master,"); sql.Append(" WalletMoney=@WalletMoney,"); sql.Append(" BankMoney=@BankMoney,"); sql.Append(" Fascination=@Fascination,"); sql.Append(" Viptime=@Viptime,"); sql.Append(" UserType=@UserType,"); sql.Append(" Trader=@Trader"); sql.Append(" where UserID=@UserID;"); trans.FromSql(sql.ToString()) .AddInputParameter("@Member", DbType.Int32, ddlMember.SelectedItem.Value) .AddInputParameter("@Master", DbType.Int32, ddlMaster.SelectedItem.Value) .AddInputParameter("@WalletMoney", DbType.Int32, newWM) .AddInputParameter("@BankMoney", DbType.Int32, newBM) .AddInputParameter("@Fascination", DbType.Int32, string.IsNullOrEmpty(txtFascination.Text.Trim()) ? "0" : txtFascination.Text.Trim()) .AddInputParameter("@UserType", DbType.Int32, ddlUserType.SelectedItem.Value) .AddInputParameter("@Viptime", DbType.Int32, addvip) .AddInputParameter("@Trader", DbType.Int32, rdoIsTrader.SelectedValue) .AddInputParameter("@UserID", DbType.Int32, UserID) .Execute(); #endregion #region 对Web_Users表的修改 if (!CommonManager.String.IsInteger(txtLotteries.Text.Trim())) { CommonManager.Web.RegJs(this, "alert('" + UiCommon.StringConfig.GoldName + "数必须为数字!');location.href=location.href;", false); return; } sql = new StringBuilder(); sql.Append("update Web_Users set "); sql.Append(" Pwd_anw=@Pwd_anw,"); //sql.Append( " Pwd_ques=@Pwd_ques," ); sql.Append(" ZJ_type=@ZJ_type,"); sql.Append(" ZJ_Number=@ZJ_Number,"); sql.Append("RealName=@RealName,"); sql.Append(" Lotteries=@Lotteries "); sql.Append(" where UserID=@UserID;"); trans.FromSql(sql.ToString()) .AddInputParameter("@Pwd_anw", DbType.String, txtPwd_anw.Text.Trim()) .AddInputParameter("@ZJ_Number", DbType.String, txtZJ_Number.Text.Trim()) .AddInputParameter("@ZJ_type", DbType.Int16, ddlZJ_Type.SelectedItem.Value) .AddInputParameter("@RealName", DbType.String, txtUserRealName.Text.Trim()) .AddInputParameter("@Lotteries", DbType.Int32, txtLotteries.Text.Trim()) .AddInputParameter("@UserID", DbType.Int32, UserID) .Execute(); #endregion trans.Commit(); CommonManager.Web.RegJs(this, "alert('修改成功!');location.href=location.href;", false); } catch (Exception ex) { trans.Rollback(); CommonManager.Web.RegJs(this, "alert('发生错误,错误信息:" + ex.Message + "。\\r\\n未对数据库进行任何操作。');location.href=location.href;", false); } } }