将参数传递给 SqlDataAdapter 会导致“必须声明标量变量”

问题描述 投票:0回答:2

下面的方法应该返回 ds ,它将绑定到 datagridview 但我收到错误消息:

必须声明标量变量“@ID”

public DataSet GetPatientSessions() {

    string connStr = ConfigurationManager.ConnectionStrings["connstr"].ToString();
    string cmdStr = @"SELECT ROW_NUMBER()OVER(ORDER BY ID) AS SEQ,
                      ID,
                      DAT,
                      S_HOUR,
                      E_HOUR,
                      KIND,
                      ENOPER,
                      ENDATETIME
                      FROM SEANCE
                      WHERE SICK_ID=@SICK_ID
                      ORDER BY ENDATETIME ASC;";

    using (SqlConnection conn = new SqlConnection(connStr))

    using (SqlCommand cmd = new SqlCommand(cmdStr, conn)) {

        try {

            conn.Open();
            cmd.CommandText = cmdStr;
            cmd.CommandType = CommandType.Text;

            DataSet ds = new DataSet();

            cmd.Parameters.Add(new SqlParameter("@SICK_ID", SqlDbType.Int)).Value = Convert.ToInt32(TB_PatientID.Text);

            SqlDataAdapter da = new SqlDataAdapter(cmd);

            //da.SelectCommand = cmd;
            da.Fill(ds, "PatientSessions");
            return ds;
        }

        catch (Exception ex) {
            string ErrorMsg = ex.Message.Substring(0, Math.Min(ex.Message.Length, 1024));

            return null;
        }   
    }
}

如何解决此错误?

c# sql sql-server sqldataadapter
2个回答
4
投票

您将参数添加到 SqlCommand,但随后不将此 SqlCommand 关联到 SqlDataAdapter。因此,当您执行 SqlDataAdapter.Fill 方法时,您的适配器不知道该参数

您只需使用 DataAdapter 的 SelectCommand 属性或将命令传递给 SqlDataAdapter 构造函数

// You can build a parameter directly with the Add method 
// using the proper overload
cmd.Parameters.Add("@ID", SqlDbType.Int).Value = Convert.ToInt32(TB_PatientID.Text); 
SqlDataAdapter da = new SqlDataAdapter(cmd);

1
投票

按照史蒂夫的建议将

cmd
传递给
SqlDataAdapter
的构造函数

或者将

cmd
分配给
SelectCommand
SqlDataAdapter

conn.Open();
cmd.CommandText = cmdStr;
cmd.CommandType = CommandType.Text;

DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(/*remove cmdStr and conn from here*/);

//----
da.SelectCommand = cmd;
//----

cmd.Parameters.Add(new SqlParameter("@ID", SqlDbType.Int)).Value = Convert.ToInt32(TB_PatientID.Text);

da.Fill(ds, "dsTable1");
© www.soinside.com 2019 - 2024. All rights reserved.