本人是个初学者:问个简单的问题..如下代码..我想在数据库中查询SuID且如果有结果就直接赋值给subjectid,
但是运行到if(da.Read())时。就不运行if这段代码了[Subject表中已经有数据].请问下这个是为什么?有人知道吗
       private void button1_Click(object sender, EventArgs e)
        {
            int subjectid=0;
            string a =" ";
            DBHelper.connection.Open();
            //a = (string)comboBox1.SelectedItem;
            a = (string)comboBox1.Text;
            string sql = "select SuID from Subject where SuName='a'";
             command = new SqlCommand(sql,DBHelper.connection);
            SqlDataReader da = command.ExecuteReader();
             if(da.Read())
             {
                subjectid = (int)da[0];
                
             }
             da.Close();
        }
          

解决方案 »

  1.   

    因为你的表里 没有SuName为a的数据
     private void button1_Click(object sender, EventArgs e) 
            { 
                int subjectid=0; 
                string a =" "; 
                DBHelper.connection.Open(); 
                a = (string)comboBox1.Text; 
                string sql =string.Format("select SuID from Subject where SuName='{0}'",a); 
                command = new SqlCommand(sql,DBHelper.connection); 
                SqlDataReader da = command.ExecuteReader(); 
                if(da.Read()) 
                { 
                    subjectid = (int)da[0]; 
                    
                } 
                da.Close(); 
                DBHelper.connection.Close();
            } 
              
      

  2.   

    呵呵用try{}catch{}还是好一点用来调式
      

  3.   

    对啊,TRY CATCH最好成绩能多用,这样一来你在错问题的时候就能更好的找到解决的办法