Hôm nay tôi sẽ trình này cách dùng
Web service để kết nối đến CSDL. nhằm giúp các ứng dụng client có thể dễ dàng dùng CSDL cần thiết đang cần dùng.
cây thư mục của Project mà chúng ta sẽ thực hiện :
Ý tưởng : Ta có Database
DBAtm.mdf có chứa 1 table với tên là city và các thuộc tính như
cityId, cityName, cityDescription. Mục đính của chúng ta là sẽ viết 1 web service có thể gọi tìm kiếm theo
cityId.
Đầu tiên các bạn tạo ra 1 class
City.cs với nội dung sau :
Các phương thức set/get của các thuộc tính trong lớp này nhằm hiện thực các cột trong bảng city.
Sau đó các bạn vào Web.config thêm vào thẻ <connectionString/> 1 thẻ <add/> với nội dung như sau :
<connectionStrings>
<add name ="connStr" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=
D:\ATMsService\ATMsService\data\DBAtm.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"/>
</connectionStrings>
Chú ý đến đoạn bôi dấu đỏ : đó chính là đường dẫn tuyệt đối đến thư mục data chứ CSDL của bạn.
Tiếp theo bạn tao 1 lớp
DAL có mục đính nhằm kết nối đến CSDL và truy vấn nó.
Phương thức truy vấn của tôi như sau :
public static Model.City
GetCity(string cityId)
{
SqlDataReader reader = null;
SqlConnection conn = null;
string cs = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
try
{
conn = new SqlConnection(cs);
string sql = "SELECT cityId, cityName, cityDescription FROM city WHERE cityId = '" + cityId + "' ";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
reader = cmd.ExecuteReader();
reader.Read();
Model.City city = new Model.City();
city.CityID = reader["cityId"].ToString();
city.CityName = reader["cityName"].ToString();
city.CityDescript = reader["cityDescription"].ToString();
return city;
}
catch (Exception exp)
{
//Adding logging
HttpContext.Current.Trace.Warn("Error", "Error in GetCity", exp);
}
finally
{
if (reader != null) reader.Close();
if (conn != null && conn.State != ConnectionState.Closed) conn.Close();
}
return null;
}
Bạn chỉ cần quan tâm đến những dòng đã được bôi đỏ.
Sau đó bạn tạo tiếp 1 class với tên
BAL.cs với mục đính gọi lại phương thức
GetCity của class
DAL
như sau :
namespace Biz
{
public class BAL
{
public static Model.City GetCity(string cityId)
{
Model.City city = DATA.DAL.GetCity(cityId);
city.CityName = city.CityName + "ACME";
return city;
}
}
}
Cuối cùng trong class ATMsService bạn gọi lại phương thức GetCity của lớp BAL với 1 câu lệnh duy nhất như sau.
[WebMethod]
public Model.City GetCity(string cityId)
{
return Biz.BAL.GetCity(cityId);
}
kết quả nhận được khi chúng ta chạy web service này như sau :
Trong table city của tôi có 1 bộ :
[hcm,Thành phố HCM, Tỉnh thành Hồ Chí Minh, Việt Nam].
Tôi sẽ tìm kiếm bộ này theo tên :
hcm.
kết quả như sau :
Bonus : phương thức lấy tất cả tên thành phố trong table city như sau :
public static List<string> GetAllCity()
{
SqlDataReader reader = null;
SqlConnection conn = null;
string cs = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
try
{
conn = new SqlConnection(cs);
string sql = "SELECT cityName FROM city" ;
SqlCommand command = new SqlCommand(sql,conn);
conn.Open();
reader = command.ExecuteReader();
List<string> _allCity = new List<string>();
while (reader.Read())
{
_allCity.Add(reader.GetString(0));
}
return _allCity;
}
catch (Exception)
{
HttpContext.Current.Trace.Warn("Error", "Error at GetAllCity !!!!");
}finally{
if(reader != null) reader.Close();
if(conn != null && conn.State != ConnectionState.Closed) conn.Close();
}
return null;
}
}
Như vậy chúng ta đã có thể dùng web service truy xuất đến csdl sql server trên nền tàng .Net.
Bài sau mình sẽ dùng KSoap2 trên android để truy xuất CSDL từ Webservice này.
Download project tại đây :
http://code.google.com/p/and-sungha-blog/downloads/detail?name=ATMsService.rar&can=2&q=#makechanges