【问题标题】:Trying to run a SQL query from a text box and display in a gridview尝试从文本框中运行 SQL 查询并在网格视图中显示
【发布时间】:2014-06-26 05:53:53
【问题描述】:

我有下面的代码,但我收到了错误

在建立与 SQL Server 的连接时发生与网络相关或特定于实例的错误。服务器未找到或无法访问。验证实例名称是否正确以及 SQL Server 是否配置为允许远程连接。 (提供者:命名管道提供者,错误:40 - 无法打开与 SQL Server 的连接)

namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
    SqlConnection vid = new SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\\Users\\jlm\\Desktop\\Wk5ex01vbMills\\AdventureWorksDW_Data.mdf;Integrated Security=True;Connect Timeout=30");

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {

       try 
          {         

           string str = TextBox1.Text;
           SqlCommand xp = new SqlCommand(str, vid);

           vid.Open();
           xp.ExecuteNonQuery();

           SqlDataAdapter da = new SqlDataAdapter();
           da.SelectCommand = xp;
           DataSet ds = new DataSet();
           da.Fill(ds);
           GridView1.DataSource = ds;
           GridView1.DataBind();
           vid.Close();
          }

       catch (Exception c)
          {
                Label1.Text = (c.Message);
          }
    }
  }
}

【问题讨论】:

  • 你真的允许输入SQL语句执行吗?
  • 整个sql语句都要输入到文本框中,比如SELECT * FROM DimCustomer
  • 如果有人输入DELETE FROM DimCustomersDROP Table DimCustomers怎么办?
  • 限制事项是我的待办事项列表中的下一个,但我什至无法让搜索工作。
  • 好的,我认为你在=(LocalDB)\v11.0 中缺少第二个\ - 应该是(localdb)\\v11.0。验证其余连接字符串的有效性

标签: c# asp.net sql gridview


【解决方案1】:

您需要在(LocalDB)\v11.0 部分的连接字符串中转义\。应该是localdb)\\v11.0

也就是说 - 允许输入原始 SQL 以针对您的数据库执行确实很冒险。即使您采取一切预防措施不允许危险的命令 - 总有可能会漏掉一些东西。

【讨论】:

    【解决方案2】:
    public partial class _Default : Page
    {
        SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=C:\\Users\\rinka.sai\\Desktop\\WebApplication1\\App_Data\\Database1.mdf;Integrated Security=True");
        protected void Page_Load(object sender, EventArgs e)
        {
    
    
        }
    
        protected void Button1_Click(object sender, EventArgs e)
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand(TextBox1.Text,conn);
            SqlDataReader sdr = cmd.ExecuteReader() ;
            GridView1.DataSource = sdr;
            GridView1.DataBind();
            sdr.Close();
            conn.Close();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-17
      • 1970-01-01
      • 2020-12-08
      相关资源
      最近更新 更多