c# - 我的 id 不为空,为什么会收到运行时错误?

标签 c# sql winforms ado.net runtime-error

我收到此运行时错误并且我的 id 不为空/em>

这是运行时错误

The parameterized query '(@_fName nvarchar(4),@_lName nvarchar(2),@_phone nvarchar(6),@_a' expects the parameter '@_id', which was not supplied.

我正试图从另一个表单中获取 id,这就是我这样写的原因

这是我第一层的代码

private void btnEdt_Click(object sender, EventArgs e)
{
        Ref_View_Model = new View_model._View_Model();
        Ref_C = new Customers();

        foreach (var RowInfo in Ref_C.radGridView1.SelectedRows)
        {
            FireCell = RowInfo.Cells[0].Value.ToString();

            if (FireCell==null)
            {
                MessageBox.Show("null");
            }
        }

        //Ref_C.radGridView1.CurrentRow.Delete();
        Ref_C.customersTableAdapter.Update(Ref_C.sales_and_Inventory_SystemDataSet);
        Ref_C.customersTableAdapter.Fill(Ref_C.sales_and_Inventory_SystemDataSet.Customers);

        Ref_View_Model.GetEditCustomers(FireCell, txtFName.Text, txtLName.Text, txtPhn.Text, txtDdrss.Text);
} 

这是我在最后一层的代码

public void EditCustomres( string _id,string _fName, string _lName,string _phone, string _address)
{

        Connection_String = @"Data Source=MOSTAFA-PC;Initial Catalog=" + "Sales and Inventory System" + ";Integrated Security=TrueData Source=MOSTAFA-PC;Initial Catalog=" + "Sales and Inventory System" + ";Integrated Security=True;";
        Query = "update Customers " +
                                "set FName=@_fName  ,LName=@_lName  ,Phone=@_phone ,[Address]=@_address" +" "+
                                  "where Id like @_id";
        using (Con=new SqlConnection(Connection_String))
        using (Cmd=new SqlCommand(Query,Con))
        {
            Cmd.Parameters.Add("@_fName", SqlDbType.NVarChar);
            Cmd.Parameters.Add("@_lName", SqlDbType.NVarChar);
            Cmd.Parameters.Add("@_phone", SqlDbType.NVarChar);
            Cmd.Parameters.Add("@_address", SqlDbType.NVarChar);
            Cmd.Parameters.Add("@_id", SqlDbType.Int);

            Con = Cmd.Connection;
            Con.Open();

            Cmd.Parameters["@_fName"].Value = _fName;
            Cmd.Parameters["@_lName"].Value = _lName;
            Cmd.Parameters["@_phone"].Value = _phone;
            Cmd.Parameters["@_address"].Value = _address;
            Cmd.Parameters["@_id"].Value = _id;

            Cmd.ExecuteNonQuery();
            Cmd.Dispose();
            }
} 

最佳答案

在这种情况下,您真的不想使用 LIKE,除非您有非常具体的需求来更新看起来像您传入的 ID 的内容,但又不完全...

您将 @_id 作为 SqlDbType.Int 传递,但该变量实际上是 string 类型,这将导致转换发生在引擎盖下。如果您传递的是空字符串,该值将转换为 null,这将导致您在帖子中提到的错误。检查导致调用 EditCustomres 的代码,以确保它确实传递了正确的值。添加参数检查(就像我添加的那样)将帮助您更早地在调用堆栈中跟踪此类问题。

第一步是删除您的LIKE 语句,因此请更新查询以使用:

where id = @_id

然后更新你的代码,因为你希望 _id 变量是 int,你不能只给它分配一个字符串,这可能就是它被重置为 null< 的原因。更新方法以接受 int 参数而不是 string id,或者在添加参数之前解析方法中的 int:

int idValue = -1;
if (!int.TryParse(_id, NumberStyles.Integer, CultureInfo.InvariantCulture, out idValue))
{
    throw new ArgumentException("id", "Id must be a string which contains an integer value, the value of 'id' was: '" + _id + "'"); 
}

Cmd.Parameters.Add("@_id", SqlDbType.Int).Value = idValue;

您可能需要在文件中添加 using 语句:

using System.Globalization;

这是定义 NumberStylesCultureInfo 的地方。通常 Visual Studio 会建议您在哪里可以找到这些项目 crtl+ 会弹出一个屏幕,自动添加此语句。


最终结果将是:

using System.Globalization;

....
....

public void EditCustomers( string _id,string _fName, string _lName,string _phone, string _address)
{
    int idValue = -1;
    if (!int.TryParse(_id, NumberStyles.Integer, CultureInfo.InvariantCulture, out idValue))
    {
       string message = "Id must be a string which contains an integer value, the value of 'id' was: '" + _id + "'";
       throw new ArgumentException("_id", message); 
    }

    Connection_String = @"Data Source=MOSTAFA-PC;Initial Catalog=" + "Sales and Inventory System" + ";Integrated Security=TrueData Source=MOSTAFA-PC;Initial Catalog=" + "Sales and Inventory System" + ";Integrated Security=True;";
    Query = @"update Customers 
                  set FName=@_fName, LName=@_lName, Phone=@_phone,[Address]=@_address
                  where Id = @_id";

    using (Con=new SqlConnection(Connection_String))
    using (Cmd=new SqlCommand(Query, con))
    {
        Cmd.Parameters.AddWithValue("@_fName", _fName);
        Cmd.Parameters.AddWithValue("@_lName", _lName);
        Cmd.Parameters.AddWithValue("@_phone", _phone);
        Cmd.Parameters.AddWithValue("@_address", _address);
        Cmd.Parameters.AddWithValue("@_id", idValue);

        Con.Open();
        Cmd.ExecuteNonQuery();
    }
}   

我也稍微简化了代码。为您的 SQL 语句使用逐字字符串,删除对 Dispose 的调用(您已经使用 using(cmd) 并删除 Con=Cmd .Connection,因为它真的不能有任何其他值。

使用 .AddWithValue 方法也比单独创建和设置值更容易。


对于要求您连接字符串以在 SQL Server 端形成 SQL 查询的解决方案,请务必小心,这可能会导致值注入(inject)不需要的 SQL 语句,从而将您的数据暴露给外部世界或允许外部人员破坏您的数据。

还要注意用于匹配更新值的 LIKE 语句。除非您在调用此语句的代码路径上有非常强大的参数验证,传入 id="?"id="%%" 或只是 id =string.Empty 您的函数可能会更新所有记录,因此会覆盖所有记录以具有相同的值。 %1% 将匹配 1, 10, 21, 31, 11, 100003... 这极不可能是期望的行为。

在删除和更新语句中使用 = 而不是 like 几乎总是是理想的解决方案。如果您遇到 = 错误,您可能混合了数据类型(例如,string,其中 int 是预期的)。

关于c# - 我的 id 不为空,为什么会收到运行时错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34554568/

相关文章:

c# - RichTextBox换行转换?

C# 序列化不会向 xml 文件中的属性添加值

c# - 在关联来自不同基类的派生类时避免双向依赖

c# - jQuery DateTimePicker : Post datetime data to ViewModel in MVC3 action using jQuery $. 后()

c# - U-SQL 将一列拆分为两列,由 "-"分隔

sql - 删除索引会发生什么坏事?

c# - 将 ListView 项目转换到 List<string>?

c# regex.ismatch 使用变量

c# - 为什么 IEnumerable<T> 被定义为 IEnumerable<out T>,而不是 IEnumerable<T>

mysql - 如何在一个查询中组合多个 SUM?