使用阅读器从表中查询数据

时间:2018-10-03 14:03:22

标签: c#

当前,我尝试检索表的寄存器的数据,但是它什么也没检索,是吗?我不知道我的脚本是否错误或缺少什么。不要捕获任何东西。我也尝试与此查询,但我不知道哪里是正确的形式? SqlCommand comm =新的SqlCommand(“从clase_Documento中选择clase,操作,其中codigoafip ='” + codafip +“'”,conn);

Field codafip = (Field)doc.Fields["ZIMCodigoAFIP"];
Field clasedoc = (Field)doc.Fields["ZIMBlart"];
Field operacion = (Field)doc.Fields["ZIMOperacion"];

SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=localhost\\DOKUSTAR;Database=RdaDB10;User ID=bcc;Password=******;Trusted_Connection=Yes";
conn.Open();

SqlDataReader dr;
SqlCommand comm = new SqlCommand("select * from Clase_Documento", conn);
dr = comm.ExecuteReader();
while(dr.Read())
{
    if (codafip.Value == dr.GetString(4))
    {   
        string clasedoc2 = dr.GetString(1);
        string operacion2 = dr.GetString(5);
        clasedoc.Value = clasedoc2; //here put the data of the table in its respective field
        operacion.Value = operacion2; //here put the data of the table in its respective field
    }
}

仅澄清一下,mi表是这个,而我想检索的字段是“ clase”和“ operacion”,具体取决于参数codigoafip enter image description here

1 个答案:

答案 0 :(得分:2)

假设您的字段名称为claseDocField,operacionField和codafipField(以及所有字符串):

using (SqlConnection conn = new SqlConnection(@"server=.\DOKUSTAR;Database=RdaDB10;Trusted_Connection=Yes"))
using (SqlCommand comm = new SqlCommand(@"select top(1) clasedocField, operacionField
from Clase_Documento
where codafipField = @codafip", conn))
{
 comm.Parameters.Add("@codafip", SqlDbType.VarChar).Value = codafip.Value;
 conn.Open();

  SqlDataReader dr = comm.ExecuteReader();
  if(dr.Read())
  {
        clasedoc.Value = (string)dr["claseDocField"];
        operacion.Value = (string)dr["operacionField"];
  }
}

编辑:

    using (SqlConnection conn = new SqlConnection(@"server=.\DOKUSTAR;Database=RdaDB10;Trusted_Connection=Yes"))
    using (SqlCommand comm = new SqlCommand(@"select top(1) clase, operacion
    from Clase_Documento
    where codigoafip = @codafip", conn))
    {
     comm.Parameters.Add("@codafip", SqlDbType.VarChar).Value = codafip
;
     conn.Open();

      SqlDataReader dr = comm.ExecuteReader();
      if(dr.Read())
      {
            clasedoc.Value = (string)dr["clase"];
            operacion.Value = (string)dr["operacion"];
      }
      else 
      {
           clasedoc.Value = "Not found";
      }
    }