Asp.net 在网页编写C#代码示例-- 一个简单的web MsSql 命令执行环境

时间:2022-10-31 19:21:58
在给一个客户做的系统上,因为要对数据库进行查看,但之前都是用TeamView来连接到客户的服务器进行数据库操作的
但最近客户那边的TeamView好像更改过密码导致我无法正常连接,而巧了客户的网官因为有事没有上班所以也法获取新的密码。
因为业务原因急需查看数据库,所以就写了一个简单的SQl命令并部署到客户的服务器来通过Web执行Sql命令
将ConnectonString更改为自己的数据库连接并保存为**.aspx即可
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>exec mssql command-HTL</title>
</head>
<%@ Page Language="C#" enableViewState="true" %>
<%@ Import namespace="System" %>
<%@ Import namespace="System.Data" %>
<%@ Import namespace="System.Data.SqlClient" %>
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
if(txt_sql.Value.Length>0){
string _ConnectionString=System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];
if(string.IsNullOrEmpty(_ConnectionString))
{
Response.Write("ConnectionString is null<br>");
Response.End();
} Response.Write("Sql Command:<br>"+txt_sql.Value);
using (SqlConnection connection = new SqlConnection(_ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
try{
cmd.Connection = connection;
cmd.CommandText = txt_sql.Value;
cmd.Connection.Open();
// exec select
if(txt_sql.Value.ToString().ToLower().Contains("select "))
{
using(SqlDataAdapter sda=new SqlDataAdapter(cmd))
{
DataTable dtable = new DataTable();
sda.Fill(dtable);
GridView1.DataSource=dtable;
GridView1.DataBind();
}
}
//exec update,insert,delete,other
else
cmd.ExecuteNonQuery();
Response.Write("<br>sql Command Success");
}
catch (Exception e1) { Response.Write(e1.Message); }
finally{
connection.Close();
}
}//end using sqlcommand
}//end using SqlConnection
}//end if
}//end Button1_Click
</script>
<body>
<center>
<h1 style="color:red;">at before executing Sql command , please backup database </h1>
</center>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" ></asp:GridView><br>
<textarea id="txt_sql" runat="server" style="width:80%;height:200px;"></textarea>
<br>
<asp:Button ID="btnAdd" runat="server" Text="Exec Sql" OnClick="Button1_Click" />
</form>
</body>
</html>
有图有真相:
 
Asp.net 在网页编写C#代码示例-- 一个简单的web MsSql 命令执行环境
为了安全,将下面的配置添加到web.config文件并在服务品上添加相应的用户名和密码用于访问该文件
如果要访问mssql.aspx文件则必须要用”WWW_mssql“ 账号进行登陆否则无法访问
<locationpath="mssql.aspx">
<system.web>
<authorization>
<allowusers=".\WWW_mssql"/>
<denyusers="*"/>
</authorization>
</system.web>
</location>
如果任务完成请将该文件删除,防止出现安全问题
 
至于为何要在asp.net页面中直接编写C#代码?主要是简单,只是一个文件而已不需要重新编译Dll且不会对现有的系统有任何影响。
 
参考(如何在Asp.net页面中直接编写C#代码 ):