简体   繁体   English

C#DataAdapter参数错误

[英]C# DataAdapter Parameter Error

Read everything I could, I still can't get my parameter to work with a SqlDataAdapater. 尽我所能阅读所有内容,但仍然无法使我的参数与SqlDataAdapater一起使用。 If someone can tell me what my problem is it would be much appreciated. 如果有人可以告诉我我的问题,将不胜感激。 I tried to use Parameters.Add first since I've read it is the better method but gave up and tried to use a SqlCommand to no avail. 我尝试使用Parameters.Add首先,因为我已经看过它是更好的方法,但是放弃了,并尝试使用SqlCommand无效。

private void Run_BTN_Click(object sender, EventArgs e)
    {
        var select = "select C.LSTNAME from C " +
                     "inner join bd ON bd.id = C.id " +
                     "@nameParam";
        var c = new SqlConnection(CnnString.CnnVal("DB2"));
        SqlCommand command = new SqlCommand(select, c);
        var dataAdapter = new SqlDataAdapter(command);

        command.Parameters.AddWithValue("@nameParam", "where C.LSTNAME = " + Cust_TB.Text);
       /* dataAdapter.SelectCommand.Parameters.Add(new SqlParameter
        {
              ParameterName = "@nameParam",
              Value = "where C.LSTNAME = " + Cust_TB.Text,
              SqlDbType = SqlDbType.NVarChar,
              Size = 2000  // Assuming a 2000 char size of the field annotation (-1 for MAX)
        }); */

        var ds = new DataSet();
        try
        {
            dataAdapter.Fill(ds);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        Reporting_DGV.ReadOnly = true;
        Reporting_DGV.DataSource = ds;
    }

What? 什么? look at your code line below ... you are actually injecting a WHERE clause or SQL statement in your parameter and not a value. 看看下面的代码行...实际上是在参数而不是值中注入WHERE子句或SQL语句。 SqlParameters are for passing a value to your SQL statement. SqlParameters用于将值传递给您的SQL语句。

command.Parameters.AddWithValue("@nameParam", "where C.LSTNAME = " + Cust_TB.Text);

Your query should be 您的查询应为

     var select = "select C.LSTNAME from C inner join bd ON bd.id = C.id where C.LSTNAME = @nameParam";
    var c = new SqlConnection(CnnString.CnnVal("DB2"));
    SqlCommand command = new SqlCommand(select, c);
    command.Parameters.AddWithValue("@nameParam", Cust_TB.Text);
    var dataAdapter = new SqlDataAdapter(command);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM