//Service.csusing System; //引用System名称空间下的类 using System.Web; //引用Web名称空间下的类 using System.Web.Services; //引用Services名称空间下的类 using System.Web.Services.Protocols; //引用Protocols名称空间下的类 using System.Data.SqlClient; //引用SqlClient名称空间下的类 using System.Collections; //引用Collections名称空间下的类 using System.Data; //引用Data名称空间下的类 [WebService(Namespace = "http://tempuri.org/")]//默认的名称空间 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class Service : System.Web.Services.WebService { public Service () //默认构造函数 { } public class Employee //自定义类,用以存储数据 { public string employeeId; public string firstName; public string lastName; } [WebMethod] [System.Xml.Serialization.XmlInclude(typeof(Employee))] //声明“Employee”类可写入XML public ArrayList GetData() //获得数据库数据 { SqlConnection conn = new SqlConnection(); //定义“SqlConnnection”类实例 //数据库连接字符串 conn.ConnectionString = "Data Source=.;Initial Catalog=Company; Persist Security Info=True;User ID=sa;Password=sa"; //定义“SqlCommand”实例,从“Employee”表中取数据 SqlCommand command = new SqlCommand( "select * from Employee",conn); conn.Open(); //打开连接 SqlDataAdapter da = new SqlDataAdapter(); //定义“SqlDataAdapter”类实例 //将“command”值传递给“SqlDataAdapter”的“SelectCommand”属性 da.SelectCommand = command; DataSet ds = new DataSet(); //定义“DataSet”类实例 da.Fill(ds, "tables"); //取数据 ArrayList al = new ArrayList(); //定义“ArrayList”类实例 for (int i = 0; i < ds.Tables[0].Rows.Count; i++) //将全部数据存储于al变量中 { Employee em = new Employee(); //定义“Employee”类实例 //添加数据到“al”变量中 em.employeeId= ds.Tables[0].Rows[i]["employeeId"].ToString().Trim(); em.firstName = ds.Tables[0].Rows[i]["firstName"].ToString().Trim(); em.lastName=ds.Tables[0].Rows[i]["lastName"].ToString().Trim(); al.Add(em); } conn.Close(); //关闭数据库 return al; } } (18) 引用名称空间、类声明、默认构造函数等代码都是VS 2005自动生成的。 (19) “[WebService(Namespace = "http://tempuri.org/")]”表示WebService的名称空间。 (20) [WebMethod]关键字指明此函数为WebService的方法。 (21) DataSet类型是一种多表数据类型。若数据以此类型返回,Flex程序将很难处理。所以本程序中自定义了Employee类,将数据全部存储于ArrayList类型变量中。 (22) 由于Employee类是自定义的,WebService在生成WSDL(WebService标准文件)时并不认识,所以需要声明。声明语句为“[System.Xml.Serialization.XmlInclude (typeof(Employee))]”。 (23) 数据库连接语句“Data Source=.;Initial Catalog=Company;Persist Security Info=True; User ID=sa;Password=sa”必须正确。用户可根据实际设置修改用户名和密码。 (24) 获取Employee表全部数据的SQL语句为“select * from Employee”。
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/spyking945/archive/2009/07/07/4325303.aspx
|