2011-11-03 96 views
0

我正在使用C#.NET中的代码创建一个Web服务,该服务将接受特定的输入。然后它将连接到数据库,根据提供的输入,必须从我的表中提取整个结果并相应显示。根据用户输入显示查询结果

但是,我不熟悉C#.NET,所以我无法正确实现我的代码。有人可以帮我

这里是我迄今为止做的:

 using System; 
     using System.Collections; 
     using System.ComponentModel; 
     using System.Data; 
     using System.Linq; 
     using System.Web; 
     using System.Web.Services; 
     using System.Web.Services.Protocols; 
     using System.Xml.Linq; 
     using System.Data.SqlClient; 

    namespace test3 
    { 
      /// <summary> 
     /// Summary description for Service1 
     /// </summary> 
    [WebService(Namespace = "http://tempuri.org/")] 
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
    [ToolboxItem(false)] 
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService] 
    public class Service1 : System.Web.Services.WebService 
    { 
     [WebMethod] 
     public String GetAttendance(String rollno) 
     { 
      String result=""; 


      try 
      { 
       using (SqlConnection myConnection = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=student;User ID=sa;Password=123")) 
      { 

       myConnection.Open(); 

       using (SqlCommand myCommand = new SqlCommand()) 
       { 

        myCommand.Connection = myConnection; 
        myCommand.CommandText = "SELECT COUNT(*) FROM studentdata WHERE rollno = @rollno"; 


        myCommand.Parameters.Add("@rollno", SqlDbType.VarChar).Value = rollno; 

        SqlDataReader myReader = myCommand.ExecuteReader(); 
        while (myReader.Read()) 
        { 
         result = myReader.ToString(); 

        } 

       } 
      } 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex.Message); 
      return "an error occured"; 
     } 

     return result; 
    } 

    } 

} 

如果我运行此代码,我得到的输出为“System.Data.SqlClient.SqlDataReader”,这是不是我想要的

回答

2

不要使用数据读取器为这个你只能有一个结果,这是一个行数所以用ExecuteScalar()并使用int类型的结果:

int result = Convert.ToInt32(myCommand.ExecuteScalar()); 

(或者你可以得到字符串值与您当前的查询使用result = myReader.GetInt32(0).ToString(); - 不要这样做)

+0

雅我试着这样做,但现在它是击中catch块...和输出是“出现错误” –

+0

什么是异常信息? – BrokenGlass

+0

System.Data.dll –