首页  ·  知识 ·  云计算
asp.net中打造web形式的查询分析器
记者  CIOZJ    编辑:dezai   图片来源:网络
一个没有UI界面的查询分析器,不仅能以命令行模式来调用sql语句,还可以运行储存在文件中的sql语句,思路出来了,先将在文本框中输入的sql语句写入磁盘,在通过osql调用,用完删掉。

碰到过虚拟主机提供商不能及时解决你的问题吗? 有时更改一个字段都要联系n次吗?  不知道大家有没有为这些事烦恼,狂不爽以后,我想到要是自己能远程操作sql服务器该有多好~~~~  (坏笑。。。)
         于是想到了sql中的osql程序,它是一个没有UI界面的查询分析器,不仅能以命令行模式来调用sql语句,还可以运行储存在文件中的sql语句,思路出来了,先将在文本框中输入的sql语句写入磁盘,在通过osql调用,用完删掉。
    以下是运行截图:
1   input.aspx

 

2   有返回数据集的结果页面

 

3   执行存储过程的界面(因为osql程序需要参数,所以自己填啦)

 

先建立ExcuteSQL工程,程序代码:
input.aspx
<%@ Page language="c#" Codebehind="Input.aspx.cs" AutoEventWireup="false" Inherits="ExcuteSQL.Input" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
 <HEAD>
  <title>Input</title>
  <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
  <meta name="CODE_LANGUAGE" Content="C#">
  <meta name="vs_defaultClientScript" content="JavaScript">
  <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
  <style type="text/css">
  BODY { FONT-SIZE: 11px }
  TD { FONT-SIZE: 11px }
  TH { FONT-SIZE: 11px }
  </style>
 </HEAD>
 <body MS_POSITIONING="GridLayout">
  <form id="Form1" method="post" runat="server">
   <asp:TextBox id="TextBox1" style="Z-INDEX: 101; LEFT: 24px; POSITION: absolute; TOP: 8px" runat="server"
    Width="700px" Height="340px" TextMode="MultiLine"></asp:TextBox>
   <asp:RadioButtonList id="rbl" style="Z-INDEX: 103; LEFT: 72px; POSITION: absolute; TOP: 372px" runat="server"
    Width="480px" RepeatColumns="3">
    <asp:ListItem Value="0" Selected="True">不需要返回</asp:ListItem>
    <asp:ListItem Value="1">需要返回数据集</asp:ListItem>
    <asp:ListItem Value="2">执行存储过程</asp:ListItem>
   </asp:RadioButtonList>
   <asp:Button id="Button1" style="Z-INDEX: 102; LEFT: 632px; POSITION: absolute; TOP: 376px" runat="server"
    Width="64px" Text="执行"></asp:Button>
  </form>
 </body>
</HTML>

input.aspx.cs
  
protected System.Web.UI.WebControls.RadioButtonList rbl;
  protected System.Web.UI.WebControls.TextBox TextBox1;
 
  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
  }

  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {    
   this.Button1.Click += new System.EventHandler(this.Button1_Click);
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion

  private void Button1_Click(object sender, System.EventArgs e)
  {
   string sql=Server.HtmlDecode(TextBox1.Text.Trim()).Replace("/r/n","$myenter$");
   string change=rbl.SelectedValue;
   Response.Redirect("Result"+change+".aspx?sql="+sql,true);
  }
 }
}

Result0.aspx只是一个处理页面,不需要界面,cs文件如下:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace ExcuteSQL
{
 /// <summary>
 /// Result0 的摘要说明。
 /// </summary>
 public class Result0 : System.Web.UI.Page
 {
  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
   if(!this.IsPostBack)
   {
    string oldurl=Request.UrlReferrer.ToString();
    try
    {     
     SqlConnection con=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]);
     SqlCommand cmd=new SqlCommand(Server.HtmlDecode(Request["sql"]).Replace("$myenter$","/r/n"),con);
     con.Open();
     cmd.ExecuteNonQuery();
     con.Close();
     Response.Write("<script>alert('执行成功');location.href='"+oldurl+"'</script>");
    }
    catch
    {
     Response.Write("<script>alert('失败');location.href='"+oldurl+"'</script>");
    }
   }
  }

  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {    
   this.Load += new System.EventHandler(this.Page_Load);
  }
  #endregion
 }
}

Result1.aspx用datagrid来显示返回结果,其中总记录数能在底部显示
<%@ Page language="c#" Codebehind="Result1.aspx.cs" AutoEventWireup="false" Inherits="ExcuteSQL.Result1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
 <HEAD>
  <title>Result1</title>
  <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
  <meta name="CODE_LANGUAGE" Content="C#">
  <meta name="vs_defaultClientScript" content="JavaScript">
  <meta name="vs_targetSchema" content="
http://schemas.microsoft.com/intellisense/ie5
">
  <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
  <style type="text/css">
  BODY { FONT-SIZE: 11px }
  TD { FONT-SIZE: 11px }
  TH { FONT-SIZE: 11px }
  </style>
 </HEAD>
 <body MS_POSITIONING="GridLayout">
  <form id="Form1" method="post" runat="server" style="FONT-SIZE: 12px">
   <asp:DataGrid id="DataGrid1" runat="server" Width="672px" BorderColor="#3366CC" BorderStyle="None"
    BorderWidth="1px" BackColor="White" CellPadding="4" AllowPaging="True">
    <SelectedItemStyle Font-Bold="True" ForeColor="#CCFF99" BackColor="#009999"></SelectedItemStyle>
    <ItemStyle ForeColor="#003399" BackColor="White"></ItemStyle>
    <HeaderStyle Font-Bold="True" ForeColor="#CCCCFF" BackColor="#003399"></HeaderStyle>
    <FooterStyle ForeColor="#003399" BackColor="#99CCCC"></FooterStyle>
    <PagerStyle HorizontalAlign="Left" ForeColor="#003399" BackColor="#99CCCC" Mode="NumericPages"></PagerStyle>
   </asp:DataGrid>
   <asp:Button id="Button1" runat="server" Width="104px" Text="返回输入页面"></asp:Button>
  </form>
 </body>
</HTML>

Result1.aspx.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace ExcuteSQL
{
 /// <summary>
 /// Result1 的摘要说明。
 /// </summary>
 public class Result1 : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.Button Button1;
  protected System.Web.UI.WebControls.DataGrid DataGrid1;
  static string oldurl="";
  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
   if(!this.IsPostBack)
   {
    oldurl=Request.UrlReferrer.ToString();
    try
    {
     bind();
    }
    catch
    {
     Response.Write("<script>alert('失败');location.href='"+oldurl+"'</script>");
    }
   }
  }
  private void bind()
  {
   SqlConnection con=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]);
   SqlDataAdapter cmd=new SqlDataAdapter(Server.HtmlDecode(Request["sql"]).Replace("$myenter$","/r/n"),con);
   DataSet ds=new DataSet();
   cmd.Fill(ds);
   ViewState["Row"] = ds.Tables[0].Rows.Count;
   DataGrid1.DataSource=ds;
   DataGrid1.DataBind();
  }
  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {    
   this.DataGrid1.ItemCreated += new System.Web.UI.WebControls.DataGridItemEventHandler(this.DataGrid1_ItemCreated);
   this.DataGrid1.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.DataGrid1_PageIndexChanged);
   this.Button1.Click += new System.EventHandler(this.Button1_Click);
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion

  private void DataGrid1_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
  {
   DataGrid1.CurrentPageIndex=e.NewPageIndex;
   bind();
  }

  private void DataGrid1_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
  {
   ListItemType elemType = e.Item.ItemType;

 

   if (elemType == ListItemType.Pager)

   {

    TableCell pager = (TableCell)e.Item.Controls[0];

    int up = 0;

    int down = 0;

    for (int i=0;i<pager.Controls.Count;i+=2)

    {

     Object o = pager.Controls[i];

     if (o is LinkButton)

     {

      LinkButton h = (LinkButton) o;

      if (h.Text!="...")

      {

       h.ToolTip = "跳转到第"+h.Text+"页";

      }

      if (i==2)

      {

       up = int.Parse(h.Text)-1;

      }

      if (i==pager.Controls.Count-3)

      {

       down = int.Parse(h.Text)+1;

      }

     }

     else

     {

      Label l = (Label) o;

 

      if (i==2)

      {

       up = int.Parse(l.Text)-1;

      }

      if (i==pager.Controls.Count-3)

      {

       down = int.Parse(l.Text)+1;

      }

 

      l.Text = "["+l.Text+"]";

      l.ForeColor = System.Drawing.Color.Red;

     }

    }

 

    Object oo = pager.Controls[0];

    if (oo is LinkButton)

    {

     LinkButton h = (LinkButton) oo;

     if (h.Text=="...")

     {

      h.ToolTip = "跳转到第"+up.ToString()+"页";

     }

    }

 

    Object ooo = pager.Controls[pager.Controls.Count-1];

    if (ooo is LinkButton)

    {

     LinkButton h = (LinkButton) ooo;

     if (h.Text=="...")

     {

      h.ToolTip = "跳转到第"+down.ToString()+"页";

     }

    }

 

    Label la = new Label();

    la.Text = "<table width=100%><tr><td align=left>总记录数:<b>"+ViewState["Row"].ToString()+" </b>";

    la.Text += "总页数:<b>"+this.DataGrid1.PageCount+" </b>";

    la.Text += "当前页:<font color=red><b>"+(this.DataGrid1.CurrentPageIndex+1).ToString()+" </b></font></td><td align=right>";

    pager.Controls.AddAt(0,la);

 

    Label lb = new Label();

    lb.Text = "</td></tr></table>";

    pager.Controls.Add(lb);

   }


  }

  private void Button1_Click(object sender, System.EventArgs e)
  {
   string aa=oldurl;
   Response.Redirect(oldurl,true);
  }
 }
}

Result2.aspx用于处理存储过程
<%@ Page language="c#" Codebehind="Result2.aspx.cs" AutoEventWireup="false" Inherits="ExcuteSQL.Result2" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
 <HEAD>
  <title>Result2</title>
  <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
  <meta name="CODE_LANGUAGE" Content="C#">
  <meta name="vs_defaultClientScript" content="JavaScript">
  <meta name="vs_targetSchema" content="
http://schemas.microsoft.com/intellisense/ie5
">
  <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
  <style type="text/css">
  BODY { FONT-SIZE: 11px }
  TD { FONT-SIZE: 11px }
  TH { FONT-SIZE: 11px }
  </style>
 </HEAD>
 <body MS_POSITIONING="GridLayout">
  <form id="Form1" method="post" runat="server" style="FONT-SIZE: 12px">
   <P><FONT face="宋体">若想执行存储过程,请输入登录远程sql服务器的用户名和密码以保证权限。</FONT></P>
   <P><FONT face="宋体">数据库
     <asp:TextBox id="tbdatabase" runat="server"></asp:TextBox><BR>
     用户名
     <asp:TextBox id="tbuser" runat="server"></asp:TextBox><BR>
     密码 &nbsp;
     <asp:TextBox id="tbpassword" runat="server" TextMode="Password"></asp:TextBox>&nbsp;
     <BR>
     临时文件路径:~/<asp:TextBox id="tbpath" runat="server"></asp:TextBox>/mysql.txt(不填会在根目录生成mysql.txt)
     <asp:Button id="Button1" runat="server" Text="执行"></asp:Button></FONT></P>
  </form>
 </body>
</HTML>
Result2.aspx.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Data.SqlClient;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;

namespace ExcuteSQL
{
 /// <summary>
 /// Result2 的摘要说明。
 /// </summary>
 public class Result2 : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.Button Button1;
  protected System.Web.UI.WebControls.TextBox tbuser;
  protected System.Web.UI.WebControls.TextBox tbpassword;
  protected System.Web.UI.WebControls.TextBox tbdatabase;
  protected System.Web.UI.WebControls.TextBox tbpath; 
  static string oldurl="";

  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
   if(!this.IsPostBack)
   {
    oldurl=Request.UrlReferrer.ToString();
    
   }
  }

  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {    
   this.Button1.Click += new System.EventHandler(this.Button1_Click);
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion

  private void Button1_Click(object sender, System.EventArgs e)
  {
   try
   {
    string str=Server.HtmlDecode(Request["sql"]); 
    string path="";
    if(tbpath.Text.Trim()==string.Empty)
     path=Server.MapPath("~/mysql.txt");
    else
     path=Server.MapPath("~/"+tbpath.Text.Trim()+"/mysql.txt");

    str=str.Replace("$myenter$","/r/n");
    System.IO.StreamWriter sw;
    sw=System.IO.File.CreateText(path);
    sw.Write(str);
    sw.Close();

    System.Diagnostics.Process sqlProcess=new System.Diagnostics.Process();
    sqlProcess.StartInfo.FileName="osql.exe";
    sqlProcess.StartInfo.Arguments=String.Format(" -U {0} -P {1} -d {2} -i {3}",tbuser.Text.Trim(),tbpassword.Text.Trim(),tbdatabase.Text.Trim(),path);
    sqlProcess.StartInfo.WindowStyle=System.Diagnostics.ProcessWindowStyle.Hidden;
    sqlProcess.Start();
    sqlProcess.WaitForExit();
    sqlProcess.Close();

    File.Delete(path);

    Response.Write("<script>alert('执行成功');location.href='"+oldurl+"'</script>");
   }
  
 catch
   {
    Response.Write("<script>alert('失败');location.href='"+oldurl+"'</script>");
   }
  }
 }
}

本文作者:记者 来源:CIOZJ
CIO之家 www.ciozj.com 微信公众号:imciow
    >>频道首页  >>网站首页   纠错  >>投诉
版权声明:CIO之家尊重行业规范,每篇文章都注明有明确的作者和来源;CIO之家的原创文章,请转载时务必注明文章作者和来源;
延伸阅读
也许感兴趣的
我们推荐的
主题最新
看看其它的