ADO.Net kết nối thừơng xuyên (Conected Architechture)

ADO.Net kết nối thừơng xuyên (Conected Architechture)

Từ ứng dụng, ta có thể kết nối và thao tác với cơ sở dữ liệu bằng 2 phương pháp sau:

1.  Kết nối thường xuyên

2.  Kết nối không thường xuyên

Phần 1. Kết nối thường xuyên (Conected Architechture)

1.  Các bước thực hiện

Bước 1: Sử dụng Connection để kết nối đến cơ sở dữ liệu

Bước 2: Thiết lập câu lệnh thực thi: Insert, Select, Update, Delete Bước 3: Thực hiện lệnh

o   Mở kết nối

o   Thực hiện lệnh

o   Xử lý dữ liệu trả về

o   Đóng kết nối

2.  Ví dụ mẫu

Thiết kế giao diện gồm các phần như hình sau:

ADO.Net kết nối thừơng xuyên (Conected Architechture)

  • Khi Load form các dữ liệu từ bảng Customers trong CSDL Northwind của SQL Server 2000 sẽ được hiển thị trên ListView và DataGridView
  • Khi chọn 1 dòng trên ListView hoặc DataGridView, dữ liệu của dòng tương ứng sẽ hiển thị trên các TextBox
  • Khi click vào nút Insert, dữ liệu trong các Textbox được thêm vào cơ sở dữ liệu
  • Khi click vào nút Update, record được chọn sẽ được chỉnh sửa và cập nhật vào CSDL
  • Khi click nút Delete, record được chọn sẽ bị xóa khỏi CSDL

Ví dụ 1: đọc dữ liệu từ bảng Customers trong CSDL Northwind của SQL Server 2000 và hiển thị lên ListView và DataGridView

// 1. Thiết lập kết nối

string strConn = "server=.; Database = Northwind; uid=sa; pwd=;";

SqlConnection cnNorth = new SqlConnection(strConn);
// 2. Thiết lập câu lệnh

string sqlSelect = "select CustomerID, CompanyName, Address, City from
                                             Customers";

SqlCommand cmdNorth = new SqlCommand(sqlSelect, cnNorth); // 3. Thực hiện lệnh

cmdNorth.Connection.Open();

SqlDataReader reader = cmdNorth.ExecuteReader();

// Lấy dữ liệu để hiển thị, xử lý... qua đối tượng Reader // Xem ví dụ 1.1 hoặc ví dụ 1.2

// …

// Đóng kết nối

cmdNorth.Connection.Close();

Ví dụ 1.1: Đoạn chương trình sau mô tả việc đọc dữ liệu từ đối tượng reader và hiển thị lên ListView

CustomerInfo cm; // Xem ví dụ 1.3

while (reader.Read())

{

cm = new CustomerInfo();

cm.CustId = reader.GetString(0);

cm.ContactName = reader.GetString(1);

if (reader.IsDBNull(2))

cm.CustAddress = "";

else

cm.CustAddress =reader.GetString(2);

if (reader.IsDBNull(3))

cm.City = "";

else

cm.City =reader.GetString(3);

ListViewItem lvItem = new ListViewItem(cm.CustId);

lvItem.SubItems.Add(cm.ContactName);

lvItem.SubItems.Add(cm.CustAddress);

lvItem.SubItems.Add(cm.City);

lvItem.Tag = cm;

lsvCustomer.Items.Add(lvItem);

}

Ví dụ 1.2: Đoạn chương trình sau mô tả việc đọc dữ liệu từ đối tượng reader và hiển thị lên DataGridView

ArrayList list = new ArrayList(); CustomerInfo cm; // Xem ví dụ 1.3
while (reader.Read())

{

cm = new CustomerInfo();

cm.CustId = reader.GetString(0);

cm.ContactName = reader.GetString(1);

if (reader.IsDBNull(2))

cm.CustAddress = "";

else

cm.CustAddress =reader.GetString(2);

if (reader.IsDBNull(3))

cm.City = "";

else

cm.City =reader.GetString(3);

list.Add(cm);

}

dataGridView1.DataSource = list;

Ví dụ 1.3:  CustomerInfo là lớp mô tả các thông tin về đối tượng Customer. CustomerInfo được viết như sau:

public class CustomerInfo
{

string custId;

string contactName;
string custAddress;
string city;

public CustomerInfo()
{ }

public CustomerInfo(string custId, string contactName, string custAddress, string city)

{

this.custId = custId;

this.contactName = contactName;

this.custAddress = custAddress;

this.city = city;

}

public string CustId
{

get {return custId;}

set {custId = value;} 

}

public string ContactName
{

get {return contactName;}

set {contactName = value;}  }

public string CustAddress

{

get {return custAddress;}

set {custAddress = value;} 

}

public string City
{

get {return city;}

set {city = value;}

}

}

Ví dụ 2: Lấy dữ liệu từ các Textbox: txtID, txtName, txtẢddress và txtCity để lưu vào Database và cập nhật mới dữ liệu hiển thị trên form

private void cmdInsert_Click(object sender, System.EventArgs e)
{

// 1. Kết nối

string strConn = "server=(local); Database = Northwind; uid=sa; pwd=;"; SqlConnection cnNorth = new SqlConnection(strConn);

// 2. Thiết đặt câu lệnh thực thi

string sqlInsert= "insert into Customers(CustomerID, " +

"CompanyName, Address, City) values(@CustomerID, @CompanyName, "+ "@Address, @City)";

SqlCommand cmdNorth = new SqlCommand(sqlInsert, cnNorth);
cmdNorth.Parameters.Add("@CustomerID", SqlDbType.NChar);
cmdNorth.Parameters.Add("@CompanyName", SqlDbType.NChar);

cmdNorth.Parameters.Add("@Address", SqlDbType.NChar);
    cmdNorth.Parameters.Add("@City", SqlDbType.NChar);
    cmdNorth.Parameters[0].Value = txtID.Text;
    cmdNorth.Parameters[1].Value = txtName.Text;
    cmdNorth.Parameters[2].Value = txtAddress.Text;
    cmdNorth.Parameters[3].Value = txtCity.Text;
// 3. Thực thi lệnh

cmdNorth.Connection.Open();

int kq = cmdNorth.ExecuteNonQuery(); if (kq > 0)

{

MessageBox.Show("Dữ liệu đã cập nhật!");
           // Gọi lại hàm Load dữ liệu ở Ví dụ 1  }

else

{

MessageBox.Show("Có lỗi xãy ra!");

}

cmdNorth.Connection.Close();

}

Ví dụ 3: Chọn 1 dòng trên ListView dữ liệu tương ứng sẽ hiển thị trên các TextBox.

private void lsvCustomer_SelectedIndexChanged(object sender, System.EventArgs e)

{

if (lsvCustomer.SelectedItems.Count == 0)
      return;

CustomerInfo cm = lvCustomer.SelectedItems[0].Tag as CustomerInfo; txtID.Text = cm.CustId;

txtName.Text = cm.ContactName;

txtAddress.Text = cm.CustAddress; txtCity.Text = cm.City;

}

Ví dụ 4: Lưu dữ liệu sau khi đã hiệu chỉnh trên TextBox vào CSDL

private void cmdUpdate_Click(object sender, System.EventArgs e)
{

if (lsvCustomer.SelectedItems.Count == 0)
           return;

// Lấy thông tin về đối tượng đang được chọn

CustomerInfo old = lsvCustomer.SelectedItems[0].Tag as CustomerInfo; // Lấy thông tin sau khi đã chỉnh sửa

CustomerInfo cm = new CustomerInfo(txtID.Text, txtName.Text,

txtAddress.Text, txtCity.Text);

// 1. Đối tượng kết nối

string strConn = "server=(local); Database = Northwind; uid=sa; pwd=;" SqlConnection cnNorth = new SqlConnection(strConn);

// 2. Câu lệnh thực thi

string sqlUpdate ="update Customers set CustomerID = "+

"@CustomerID, CompanyName = @CompanyName, Address = @Address, "+
           "City = @City where CustomerID = @OrigCustomerID";
 SqlCommand cmdNorth = new SqlCommand(sqlUpdate, cnNorth);
cmdNorth.Parameters.Add("@CustomerID", SqlDbType.NChar);
cmdNorth.Parameters.Add("@CompanyName", SqlDbType.NChar);
cmdNorth.Parameters.Add("@Address", SqlDbType.NChar);
cmdNorth.Parameters.Add("@City", SqlDbType.NChar);
cmdNorth.Parameters.Add("@OrigCustomerID", SqlDbType.NChar);
cmdNorth.Parameters[0].Value = cm.CustId;

cmdNorth.Parameters[1].Value = cm.ContactName;
cmdNorth.Parameters[2].Value = cm.CustAddress;
cmdNorth.Parameters[3].Value = cm.City;

cmdNorth.Parameters[4].Value = old.CustId; // 3. Thực thi lệnh

cmdNorth.Connection.Open();

int kq = cmdNorth.ExecuteNonQuery(); if (kq > 0)

{

MessageBox.Show("Cập nhật thành công!");

//Gọi lại phương thức Load dữ liệu ở Ví dụ 1
}

else

MessageBox.Show("Lỗi!");
cmdNorth.Connection.Close();

}

Ví dụ 5: Xóa dòng được chọn

private void cmdDelete_Click(object sender, System.EventArgs e)
{

if (lsvCustomer.SelectedItems.Count == 0)
           return;

// Lấy thông tin về đối tượng đang được chọn

CustomerInfo cm = lsvCustomer.SelectedItems[0].Tag as CustomerInfo; // 1. Đối tượng kết nối

string strConn = "server=(local); Database = Northwind; uid=sa; pwd=;" SqlConnection cnNorth = new SqlConnection(strConn);

// 2. Câu lệnh thực thi

string sqlUpdate ="Delete from Customers where CustomerID=@CustomerID"; SqlCommand cmdNorth = new SqlCommand(sqlUpdate, cnNorth);
cmdNorth.Parameters.Add("@CustomerID", SqlDbType.NChar);
cmdNorth.Parameters[0].Value = cm.CustId;

// 3. Thực thi lệnh

cmdNorth.Connection.Open();

int kq = cmdNorth.ExecuteNonQuery(); if (kq > 0)

{

MessageBox.Show("Cập nhật thành công!");

//Gọi lại phương thức Load dữ liệu ở Ví dụ 1
}

else

MessageBox.Show("Lỗi!");
cmdNorth.Connection.Close();
}

3.  Bài tập

Bài 1: Thiết kế CSDL và Xây dựng ứng dụng quản lý thông tin khách hàng với các yêu cầu sau:

- Form Đăng nhập: để đăng nhập trước khi sử dụng ứng dụng

- Kiểm tra dữ liệu rỗng trước khi thực hiện việc xử lý đăng nhập

- Nếu đăng nhập thành công thì cho phép sử dụng phần Quản lý

- Form Quản lý: có giao diện như hình bên dưới, form này để xem, thêm, sửa, xóa thông tin của khách hàng. Các thông tin cần quản lý bao gồm: mã số, họ tên, ngày sinh, địa chỉ, điện thoại, email, hình ảnh

  • Thông tin khách hàng sẽ hiển thị ngay khi vào form Quản lý
  • Thêm mới: thêm mới 1 khách hàng vào CSDL
  • Cập nhật: Chỉnh sửa thông tin 1 khách hàng trong CSDL
  • Xóa: Xóa thông tin một khách hàng

Bài 2: Cho một csdl gồm các bảng sau đây:

(1) Bảng sinh viên (sinh_vien)
- Họ tên sinh viên (ho_ten)
- Mã số sinh viên (ma_sv)
- Mật khẩu
- Giới tính (gioi_tinh)
- Ngày sinh (ngay_sinh)
- Nơi sinh (noi_sinh)
- Email (email)

(2) Bảng môn học (mon_hoc)
- Tên môn học (ten_mh)
- Mã môn học (ma_mh)
- Số tín chỉ (so_tc)
- Số lượng sinh viên tối đa (so_luong_sv)

(3) Bảng đăng ký (dang_ky)
- Mã môn học (ma_mh)
- Mã sinh viên (ma_sv)
- Ngày đăng ký (ngay_dk)

Xây dựng chương trình cho phép:

Quản lý:

  • Thêm một sinh viên vào csdl.
  • Thêm một môn học vào csdl.
  • Tra cứu danh sách sinh viên đã đăng ký môn học nào đó.
  • Tra cứu danh sách môn học mà một sinh viên đã đăng ký.
  • Chỉnh sửa thông tin của nhiều môn học cùng lúc (sử dụng DataGridView)
  • Chỉnh sửa thông tin của nhiều sinh viên cùng lúc (sử dụng DataGridView)

Sinh viên: Sau khi đăng nhập, sinh viên có thể thực hiện các chức năng sau

  • Có thể chỉnh sửa thông tin cá nhân của mình
  • Có thể xem danh sách các môn học
  • Có thể đăng ký môn học cho mình, việc đăng ký phải thỏa điều kiện sau: sinh viên không được đăng ký vượt quá 30 tín chỉ và môn đăng ký không được vượt quá số lượng đăng ký tối đa.
  • Có thể xem danh sách môn học mà mình đã đăng ký, có thể thay đổi (thêm môn học, xóa môn học)

Bài 3: Xây dựng cơ sở dữ liệu có tên là QLHS. Có cấu trúc gồm 2 bảng như sau:

Quản lý:

  • Thêm một lớp học vào csdl.
  • Thêm một học sinh vào csdl.

Bài 4: Xây dựng cơ sở dữ liệu có tên là DANHSACHDUTHI. Có cấu trúc gồm 3 bảng như sau:

Khóa chính:

  • DanhSach: SoBD
  • DiemThi: SoBD
  • ChiTietDT: DTDuThi

Script: DANHSACHDUTHI

Quản lý:

  • Thêm một Danh sách vào csdl.
  • Thêm một Chi tiết đối tượng vào csdl.
  • Thêm một Điểm thi vào csdl.
  • Xuất record trong bảng Danh sách lên màn hình(Hướng dẫn: Hướng dẫn sử dụng DataGridView control )
  • đọc dữ liệu từ bảng DanhSach trong CSDL DANHSACHDUTHI và hiển thị lên ListView và DataGridView
  • Xóa dòng được chọn từ bảng DanhSach

Phần 2. Kết nối không thường xuyên (Disconected Architechture)

1.  Các bước thực hiện

Bước 1: Sử dụng Connection để kết nối đến cơ sở dữ liệu Bước 2: Tạo đối tượng DataSet

Bước 3: Tao đối tượng DataAdapter và các câu lệnh thực thi dữ liệu Bước 4: Đỗ dữ liệu vào DataSet

Bước 5: Tương tác dữ liệu trên DataSet

Bước 6: Cập nhật dữ liệu từ DataSet lên Server

2.  Một số đoạn code mẫu

// 1. Kết nối

string strConn = "server=(local); Database = Northwind; uid=sa; pwd=;"; // 2. Tạo đôi tượng DataSet

DataSet dsCustomers = new DataSet();

// 3. Tạo đôi tượng DataAdapter và các câu lệnh thực thi dữ liệu
        SqlDataAdapter daCustomers = new SqlDataAdapter(

"select CustomerID, CompanyName from Customers", conn);

//Sử dụng SqlCommandBuider để xây dựng các câu lệnh Insert, Update, Delete SqlCommandBuilder cmdBldr = new SqlCommandBuilder(daCustomers);

// 4. Đỗ dữ liệu vào DataSet

daCustomers.Fill(dsCustomers, "Customers");

// 5. Tương tác với dữ liệu trên DataSet
        dgCustomers.DataSource = dsCustomers;

dgCustomers.DataMember = "Customers";

// 6. Cập nhật dữ liệu từ DataSet lên Server daCustomers.Update(dsCustomers, "Customers");
Bạn thấy bài viết này như thế nào?: 
Average: 10 (1 vote)
Ảnh của Tommy Tran

Tommy owner Express Magazine

Drupal Developer having 9+ year experience, implementation and having strong knowledge of technical specifications, workflow development. Ability to perform effectively and efficiently in team and individually. Always enthusiastic and interseted to study new technologies

  • Skype ID: tthanhthuy

Advertisement

 

jobsora

Dich vu khu trung tphcm

Dich vu diet chuot tphcm

Dich vu diet con trung

Quảng Cáo Bài Viết

 
Một ví dụ đơn giản sử dụng Pathauto API Drupal Module

Một ví dụ đơn giản sử dụng Pathauto API Drupal Module

Pathauto is a wonderful tool. It’s definitely my oldest friend when it comes to Drupal modules. As the module has progressed, the API has become easier to use.

Hướng dẫn Rich Video Snippets cho Drupal sites

Hướng dẫn Rich Video Snippets cho Drupal sites

Rich video snippets can make the search engine results more appealing for your website pages that contain video.

Flippa

Tìm ý tưởng Keyword Research cho website từ Flippa

Khi bạn bắt đầu làm một trang web để kiếm tiền từ Google Adsense, bạn thường quan tâm rằng không biết sau những tháng ngày SEO từ khóa lên hạng 1 rồi, trang web có được lượng visit như mong muốn không.

Công ty diệt chuột T&C

 

Diet con trung