2017-03-09 30 views
0

我有一个问题,从我的查询中获取指定值。我为我的GridView收到一行,但是当我尝试读取一个值使其进入某个变量时,它说我没有任何价值。从WebForms中的查询获取指定值

else if (Request.QueryString.AllKeys.Contains("a")) 
{ 
    String sql_user = "SELECT c1.ID, c1.SHORT_NAME, ao1.NAME, c1.REGON FROM (tabel1 c1 LEFT JOIN tabel2 ao1 ON c1.ID = ao1.ID WHERE c1.ID = ?"; 
    connection.OPEN(); 

    OleDbCommand sql_s = new OleDbCommand(sql_user, polaczenie); 

    sql_s.Parameters.add("?", OleDbType.Integer).Value = Request.QueryString["a"]; 

    OleDbDataAdapter sqlDa = new OleDbDataAdapter(sql_s); 

    DataTable dt = new DataTable(); 
    sqlDa.Fill(dt); 

    GRID_VIEW1.DataSource = dt; 

    GRID_VIEW1.DataBind(); 

    OleDbDataReader customer = sql_s.ExecuteReader(); 

    // i want to get SHORT_NAME so that one below i think dosent work 

    // but any way it make me an Exception of any value not found but on GridView it shows me clearly one ROW 
    learerLabel.Text = (String) cmd.ExecuteScalar(); 

    connection.Close(); 
} 

我做的像一些会议或Reader多种方式,但我不现在remmeber我所有的尝试,但总是它说我有我的查询中没有价值。我究竟做错了什么?由于

+0

尝试用'“@ p1”'替换Parameters.add(“?”,OleDbType.Integer)中的'“?”'。 – Xiaoy312

回答

0

不是更好做是像类:

public class MyClass 
{ 
    public int Id { get; set; } 
    public string ShortName { get; set; } 
    public string Name { get; set; } 
    public int Regon { get; set; } 
} 

下一步,从你的查询数据试试这个:

  CustomClass item = new CustomClass(); 

     String sql_user = "SELECT c1.ID, c1.SHORT_NAME, ao1.NAME, c1.REGON FROM (tabel1 c1 LEFT JOIN tabel2 ao1 ON c1.ID = ao1.ID WHERE c1.ID = @id"; 

     using (var conn = new OleDbConnection("connectionString")) 
     { 
      conn.Open(); 
      using (var cmd = new OleDbCommand(sql_user, conn)) 
      { 
       cmd.Parameters.Add("@id", OleDbType.Integer).Value = Request.QueryString["a"]; 
       cmd.Prepare(); 

       var reader = cmd.ExecuteReader(); 

       if(reader.Read()) 
       { 
        item.Id = (int)reader["ID"]; 
        item.ShortName = reader["SHORT_NAME"].ToString(); 
        item.Name= reader["NAME"].ToString(); 
        item.Regon = (int)reader["REGON"]; 
       } 
       conn.Close(); 
      } 

     } 

编辑: 如果你不想使用它,你需要改变taht行:

OleDbDataReader customer = sql_s.ExecuteReader(); 

到:

  OleDbDataReader customer; 
     var dr = sql_s.ExecuteReader(); 

     if (dr.Read()) 
      customer = dr; 

试试这个,贷款机构写工作

0

试试这个,更换参数名@ID详情,请参阅参数传递

SELECT c1.ID, c1.SHORT_NAME, ao1.NAME, c1.REGON FROM (tabel1 c1 LEFT JOIN tabel2 ao1 ON c1.ID = ao1.ID WHERE c1.ID = @ID 
sql_s.Parameters.add("@ID", OleDbType.Integer).Value = Request.QueryString["a"]; 

更多细节上传递参数下面的MSDN文档的链接,请在下面的MSDN https://msdn.microsoft.com/en-us/library/bbw6zyha(v=vs.110).aspx

+0

谢谢,我会试一试。但是,你能告诉我什么是从这个查询(行)执行该值的最佳方式? – Adriano

+0

我不确定是否正确理解了您的问题,但您可以使用数据读取器或数据适配器。如果您的查询只返回几行,您可以使用数据阅读器,否则我会推荐使用数据适配器。 – BipinR