asp.net Web頁執行SQL程式碼

來源:互聯網
上載者:User

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ManageSQL.aspx.cs" Inherits="manage_ManageSQL" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Web頁執行SQL</title>
<style type="text/css">
*{
padding:0;
margin:0;
}
body{
font-size:12px;
color:#333;
}
.navPath
{
 background:#A4B6D7;
 padding:4px;
}
</style>
</head>
<body>
<form id="form" runat="server">
<div class="navPath">您的當前位置:系統管理&raquo;&raquo;執行SQL</div>
<div style="vertical-align:top; margin-top:10px; margin-left:10px;">
    <asp:TextBox ID="txtSQL" runat="server" TextMode="MultiLine" Height="80px" Width="90%" BorderStyle="Inset" OnTextChanged="txtSQL_TextChanged"></asp:TextBox>
    <br />
    <asp:Button ID="btnExeSql" runat="server" CssClass="button" Text="執行SQL" OnClick="btnExeSql_Click" />
    <asp:Label ID="lblExeNum" runat="server"></asp:Label>
<a href="javascript:void(0)" onclick="Open(document.getElementById('table').innerHTML)">查看錶結構</a>
    <div id="table" style="display:none;">
    <asp:GridView ID="grdTable" runat="server" Font-Size="12px" Width="100%">
        <RowStyle HorizontalAlign="Center" CssClass="tItem" />
        <PagerStyle CssClass="tPage" />
        <HeaderStyle CssClass="tHeader" />
        <AlternatingRowStyle CssClass="tAlter" />
        <SelectedRowStyle BackColor="#F1F5FB" />
    </asp:GridView>
    </div>
    <div class="tipInfo" style="width:90%; display:none;" id="tip">此功能建議僅供系統管理員在十分熟悉SQL語句的情況下操作,否則可能造成資料庫資料丟失。</div>
    <hr style="border-collapse:collapse; width:90%; text-align:left;" />
</div>
    <asp:GridView ID="grdSQL" runat="server" Width="100%" Visible="False">
        <RowStyle HorizontalAlign="Center" CssClass="tItem" />
        <PagerStyle CssClass="tPage" />
        <HeaderStyle CssClass="tHeader" />
        <AlternatingRowStyle CssClass="tAlter" />
        <SelectedRowStyle BackColor="#F1F5FB" />
    </asp:GridView>
<script type="text/javascript">
var Osel=document.form;
Osel.onsubmit=function()
{
    if(Osel.<%=txtSQL.ClientID %>.value=="")
    {
        alert("輸入不可為空白");
        Osel.<%=txtSQL.ClientID %>.focus();
        return false;
    }
    else if(Osel.<%=txtSQL.ClientID %>.value.indexOf("update")!=-1 || Osel.<%=txtSQL.ClientID %>.value.indexOf("delete")!=-1 || Osel.<%=txtSQL.ClientID %>.value.indexOf("truncate")!=-1)
    {
        if(confirm("即將執行的操作帶有一定的風險,是否繼續?"))
            return true;
        else
            return false;
    }
}

function Open(value)
{
  var TestWin=open('','','toolbar=no, scrollbars=yes, menubar=no, location=no, resizable=no');
  TestWin.document.title="資料庫表結構";
  TestWin.document.write(value);
}

function clear()
{
    document.getElementById("tip").style.display="none"
}
window.setInterval("clear()",3000);

</script>
</form>
</body>
</html>

網頁執行SQL語句程式manageSql.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

/// <summary>
/// Author:walkingp
/// Web Site:http://www.51obj.cn/
/// E-mail:walkingp@126.com
/// </summary>
public partial class manage_ManageSQL : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GetTableName();
        }
    }

    #region SqlConnection
    /// <summary>
    /// 初始化SqlConnection
    /// </summary>
    private static SqlConnection connection;
    public static SqlConnection Connection
    {
        get
        {
            string connectionString = "server=.;DataBase=model;uid=sa;pwd=;";
            if (connection == null)
            {
                connection = new SqlConnection(connectionString);
                connection.Open();
            }
            else if (connection.State == System.Data.ConnectionState.Closed)
            {
                connection.Open();
            }
            else if (connection.State == System.Data.ConnectionState.Broken)
            {
                connection.Close();
                connection.Open();
            }
            return connection;
        }
    }

    /// <summary>
    /// 執行Sql
    /// </summary>
    /// <param name="sql">Sql</param>
    /// <returns>影響記錄條數</returns>
    public static int ExecuteCommand(string safeSql)
    {
        SqlCommand cmd = new SqlCommand(safeSql, Connection);
        int result = cmd.ExecuteNonQuery();
        return result;
    }
    /// <summary>
    /// 執行Sql(overload)
    /// </summary>
    /// <param name="sql">Sql</param>
    /// <param name="values">SqlParameter</param>
    /// <returns>影響記錄條數</returns>
    public static int ExecuteCommand(string sql, params SqlParameter[] values)
    {
        SqlCommand cmd = new SqlCommand(sql, Connection);
        cmd.Parameters.AddRange(values);
        return cmd.ExecuteNonQuery();
    }

    /// <summary>
    /// 擷取DataTable
    /// </summary>
    /// <param name="safeSql">Sql</param>
    /// <returns>DataTable</returns>
    public static DataTable GetDataSet(string safeSql)
    {
        DataSet ds = new DataSet();
        SqlCommand cmd = new SqlCommand(safeSql, Connection);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(ds);
        return ds.Tables[0];
    }
    #endregion

    /// <summary>
    /// 擷取資料表結構
    /// </summary>
    protected void GetTableName()
    {
        DataTable dt = Connection.GetSchema("Tables", null);
        Connection.Close();
        grdTable.DataSource = dt;
        grdTable.DataBind();
    }

    /// <summary>
    /// 執行操作
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnExeSql_Click(object sender, EventArgs e)
    {
        string sql = txtSQL.Text.Trim().ToLower();
        int intExeNum;

        try
        {
            if (sql.Substring(0, 6).IndexOf("select") != -1)
            {
                DataTable dt = GetDataSet(sql);
                grdSQL.DataSource = dt;
                grdSQL.DataBind();
                lblExeNum.Text = "返回記錄條數:<strong>" + dt.Rows.Count + "</strong>";
                grdSQL.Visible = true;
            }
            else if (sql.Substring(0, 6).IndexOf("delete") != -1 || sql.Substring(0, 6).IndexOf("update") != -1 || sql.Substring(0, 8).IndexOf("truncate") != -1)
            {
                intExeNum = ExecuteCommand(sql);
                lblExeNum.Text = "影響行數:<strong>" + intExeNum + "</strong>";
                grdSQL.Visible = false;
            }
        }
        catch (Exception ex)
        {
            ClientScript.RegisterStartupScript(typeof(string), "", "document.write("<h4 style='font-size:14px;color:#c00;padding-left:20px;'>抱歉,系統發生了錯誤……錯誤資訊:" + ex.Message.Replace(""", "'") + "</h4>")", true);
        }
    }

    /// <summary>
    /// 執行按鈕可用
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void txtSQL_TextChanged(object sender, EventArgs e)
    {
        btnExeSql.Enabled = true;
    }
}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.