【问题标题】:Error "'System.Data.SqlClient.SqlException' happened when trying to debug application尝试调试应用程序时发生错误“'System.Data.SqlClient.SqlException'
【发布时间】:2016-08-31 18:00:06
【问题描述】:

我正在创建一个应用程序,在其中存储来自文本框的输入(姓名、年龄、电话),当我单击 Submit 时,它应该将我在文本框中输入的任何内容存储到数据库中,但我不断收到此错误.

System.Data.dll 中出现“System.Data.SqlClient.SqlException”类型的异常,但未在用户代码中处理。附加信息:关键字“表”附近的语法不正确。

下面是代码:

protected void Button1_Click(object sender, EventArgs e)
    {
        String p = UniqueNumber();
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings
            ["ConnectionString"].ConnectionString);
        con.Open();
        String str = "insert into Table(uniqueno, name, age, number) values( '" 
            + Label1.Text + "','" + txtName.Text + "','" + txtAge.Text + "','" + txtNumber.Text + "')";
        SqlCommand cmd = new SqlCommand(str, con);
        cmd.ExecuteNonQuery();
        con.Close();
        Session["id"] = Label1.Text;
        Session["name"] = txtName.Text;
        try
        {
            Response.Redirect("unique.aspx");
        }
        catch
        {
            Label1.Text = "Please enter correct details....";
            this.Label1.ForeColor = Color.Red;
        }
    }

【问题讨论】:

  • sql 注入漏洞。使用参数化查询
  • 你真的是说这个错误只在尝试调试应用程序时发生,而不是在运行它时发生?如果它发生在任何运行中,请将您的问题更改为“尝试插入表格时”
  • 还将这一行 Response.Redirect("unique.aspx"); 更改为 Response.Redirect("~unique.aspx"); 也希望您熟悉 PostBacks 及其工作原理。确保在调试时传递给 SQL Insert 命令的值不为空或清空并阅读Parameterized Query's 以及如何使用它们,如果Table 是名称,请将其括在[Table] 这样的括号中,因为Table 是SQL 中的保留字
  • 正如其他人所提到的,您不应该将您的表命名为“表”,并且您不应该使用字符串连接创建语句(它容易受到 SQL 注入攻击)。我看到您将所有值作为字符串类型传递。如果它们的实际类型不同(例如,如果您将列 'age' 的类型定义为 'int'),那么由于您在值旁边放置了单引号,您会收到错误消息。

标签: c# executenonquery


【解决方案1】:

"Table" 是关键字,虽然您可能已将数据存储到表中,但我认为 SQL Server 不允许您查询。

令人惊讶的是,它允许我们有一个名为 Table 的表,但是当我们尝试选择时,它会抛出一个错误。正如@seth Flower 所提到的,尽量避免 SQL 注入漏洞。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-16
    • 1970-01-01
    • 2019-09-26
    相关资源
    最近更新 更多