Hướng dn thc hành Winforms vi C# Chương 5: ADO.NET
Hue-Aptech | Trn Văn Long – Email: tvlongsp@gmail.com Trang 1
CHƯƠNG 5 – ADO.NET
T ng dng, ta có th kết ni và thao tác vi cơ s d liu bng 2 phương pháp sau:
1. Kết ni thường xuyên
2. Kết ni không thường xuyên
Phn 1. Kết ni thường xuyên
1. Các bước thc hin
Bước 1: S dng Connection để kết ni đến cơ s d liu
Bước 2: Thiết lp câu lnh thc thi: Insert, Select, Update, Delete
Bước 3: Thc hin lnh
M kết ni
Thc thi câu lnh, x lý d liu tr v
Đóng kết ni
2. Ví d mu
Thiết kế giao din gm các phn như hình sau:
- Khi Load form các d liu t bng
Customers
trong CSDL
Northwind
ca SQL Server
2000 s được hin th trên ListView và DataGridView
- Khi chn 1 dòng trên ListView hoc DataGridView, d liu ca dòng tương ng s hin th
trên các TextBox
- Khi click vào nút Insert, d liu trong các Textbox được thêm vào cơ s d liu
- Khi click vào nút Update, record được chn s được chnh sa và cp nht vào CSDL
- Khi click nút Delete, record được chn s b xóa khi CSDL
Hướng dn thc hành Winforms vi C# Chương 5: ADO.NET
Hue-Aptech | Trn Văn Long – Email: tvlongsp@gmail.com Trang 2
Ví d 1: đọc d liu t bng
Customers
trong CSDL
Northwind
ca SQL Server 2000 và
hin th lên ListView và DataGridView
// 1. Thiết lp kết ni
string strConn = "server=.; Database = Northwind; uid=sa; pwd=;";
SqlConnection cnNorth = new SqlConnection(strConn);
// 2. Thiết lp câu lnh
string sqlSelect = "select CustomerID, CompanyName, Address, City from
Customers";
SqlCommand cmdNorth = new SqlCommand(sqlSelect, cnNorth);
cmdNorth.Connection.Open();
// 3. Thc hin lnh
SqlDataReader reader = cmdNorth.ExecuteReader();
// Ly d liu để hin th, x lý... qua đối tượng Reader
// Xem ví d 1.1 hoc ví d 1.2
// …
// Đóng kết ni
cmdNorth.Connection.Close();
Ví d 1.1: Đon chương trình sau mô t vic đọc d liu t đối tượng reader và hin 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: Đon chương trình sau mô t vic đọc d liu t đối tượng reader và hin 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);
Hướng dn thc hành Winforms vi C# Chương 5: ADO.NET
Hue-Aptech | Trn Văn Long – Email: tvlongsp@gmail.com Trang 3
}
dataGridView1.DataSource = list;
Ví d 1.3:
CustomerInfo
là lp 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: Ly d liu t các Textbox: txtID, txtName, txtddress và txtCity để lưu vào Database
và cp nht mi d liu hin th trên form
private void cmdInsert_Click(object sender, System.EventArgs e)
{
// 1. Kết ni
string strConn = "server=(local); Database = Northwind; uid=sa; pwd=;";
SqlConnection cnNorth = new SqlConnection(strConn);
// 2. Thiết đặt câu lnh thc 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;
Hướng dn thc hành Winforms vi C# Chương 5: ADO.NET
Hue-Aptech | Trn Văn Long – Email: tvlongsp@gmail.com Trang 4
cmdNorth.Parameters[3].Value = txtCity.Text;
// 3. Thc thi lnh
cmdNorth.Connection.Open();
int kq = cmdNorth.ExecuteNonQuery();
if (kq > 0)
{
MessageBox.Show("D liu đã cp nht!");
// Gi li hàm Load d liu Ví d 1
}
else
{
MessageBox.Show("Có li xãy ra!");
}
cmdNorth.Connection.Close();
}
Ví d 3: Chn 1 dòng trên ListView d liu tương ng s hin 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 liu sau khi đã hiu chnh trên TextBox vào CSDL
private void cmdUpdate_Click(object sender, System.EventArgs e)
{
if (lsvCustomer.SelectedItems.Count == 0)
return;
// Ly thông tin v đối tượng đang được chn
CustomerInfo old = lsvCustomer.SelectedItems[0].Tag as CustomerInfo;
// Ly thông tin sau khi đã chnh sa
CustomerInfo cm = new CustomerInfo(txtID.Text, txtName.Text,
txtAddress.Text, txtCity.Text);
// 1. Đối tượng kết ni
string strConn = "server=(local); Database = Northwind; uid=sa; pwd=;"
SqlConnection cnNorth = new SqlConnection(strConn);
// 2. Câu lnh thc 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. Thc thi lnh
cmdNorth.Connection.Open();
int kq = cmdNorth.ExecuteNonQuery();
if (kq > 0)
{
MessageBox.Show("Cp nht thành công!");
//Gi li phương thc Load d liu Ví d 1
}
else
Hướng dn thc hành Winforms vi C# Chương 5: ADO.NET
Hue-Aptech | Trn Văn Long – Email: tvlongsp@gmail.com Trang 5
MessageBox.Show("Li!");
cmdNorth.Connection.Close();
}
Ví d 5: Xóa dòng được chn
private void cmdDelete_Click(object sender, System.EventArgs e)
{
if (lsvCustomer.SelectedItems.Count == 0)
return;
// Ly thông tin v đối tượng đang được chn
CustomerInfo cm = lsvCustomer.SelectedItems[0].Tag as CustomerInfo;
// 1. Đối tượng kết ni
string strConn = "server=(local); Database = Northwind; uid=sa; pwd=;"
SqlConnection cnNorth = new SqlConnection(strConn);
// 2. Câu lnh thc 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. Thc thi lnh
cmdNorth.Connection.Open();
int kq = cmdNorth.ExecuteNonQuery();
if (kq > 0)
{
MessageBox.Show("Cp nht thành công!");
//Gi li phương thc Load d liu Ví d 1
}
else
MessageBox.Show("Li!");
cmdNorth.Connection.Close();
}
3. Bài tp
Bài 1: Thiết kế CSDL và Xây dng ng dng qun lý thông tin khách hàng vi các yêu cu
sau:
- Form Đăng nhp: để đăng nhp trước khi s dng ng dng
- Kim tra d liu rng trước khi thc
hin vic xđăng nhp
- Nếu đăng nhp thành công thì cho phép
s dng phn Qun lý
- Form Qun lý: có giao din như hình bên dưới, form này để xem, thêm, sa, xóa thông tin
ca khách hàng. Các thông tin cn qun lý bao gm: mã s, h tên, ngày sinh, địa ch,
đin thoi, email, hình nh
o Thông tin khách hàng s hin th ngay khi vào form Qun lý
o Thêm mi: thêm mi 1 khách hàng vào CSDL
o Cp nht: Chnh sa thông tin 1 khách hàng trong CSDL
o Xóa: Xóa thông tin mt khách hàng