【问题标题】:ArgumentException when trying to open a SqlConnection尝试打开 SqlConnection 时出现 ArgumentException
【发布时间】:2013-04-16 10:18:04
【问题描述】:

此代码用于按钮:
但每次我运行它都会说是ArgumentException was unhandled by user code

这是一个用于查找数据库以查看是否有足够墨水的网站。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

    protected void Page_Load(object sender, EventArgs e)
    {
        con.Open();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("insert into Toner Values('"+txtFname.Text+"','"+txtLname.Text+"','"+TxtCity.Text+"')",con);
        cmd.ExecuteNonQuery();
        con.Close();
        Label1.Visible = true;
            Label1.Text = "Indsætning succesfuld!!!";
        TxtCity.Text = "";
        txtFname.Text = "";
        txtLname.Text = "";
    }
    protected void TextBox3_TextChanged(object sender, EventArgs e)
    {

    }
}

【问题讨论】:

  • 在使用stackoverflow时必须更加具体。您的代码在哪一行中断?
  • 你在使用 LINQTOSQL 吗??
  • 您确定“ConnectionString”作为连接字符串存在于您的 web.config 中吗?
  • CodeCaster 表示此代码易受 SQL 注入攻击。也就是说,您可以在输入字段中编写特殊的内容,以对数据库造成不良影响的方式更改 SQL(例如删除等)。您应该改用命令参数。见msdn.microsoft.com/en-us/library/…

标签: asp.net sql-server ado.net


【解决方案1】:

我最好的猜测是TxtCity 应该是txtCity

试试这个:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{

    protected void Button1_Click(object sender, EventArgs e)
    {
        string query = "insert into Toner Values (@Fname, @Lname, @City)";
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString);
        SqlCommand cmd = new SqlCommand(query, con);
        //Use parameterized query to prevent SQL injection
        cmd.Parameters.Add("Fname", SqlDbType.VarChar, 50).Value = txtFname.Text;
        cmd.Parameters.Add("Lname", SqlDbType.VarChar, 50).Value = txtLname.Text;
        //C# is case-sensitive... is it txtCity or TxtCity?
        cmd.Parameters.Add("City", SqlDbType.VarChar, 50).Value = TxtCity.Text;
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
        Label1.Visible = true;
        Label1.Text = "Indsætning succesfuld!!!";
        TxtCity.Text = "";
        txtFname.Text = "";
        txtLname.Text = "";
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-13
    • 2021-04-25
    • 2014-03-11
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    相关资源
    最近更新 更多