IELTS READING - Earth’s lakes are under threat.pptx
Hdth.chuong5 ado.netv2.0
1. Hư ng d n th c hành Winforms v i C# Chương 5: ADO.NET
Hue-Aptech | Tr n Văn Long – Email: tvlongsp@gmail.com Trang 1
CHƯƠNG 5 – ADO.NET
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
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
• M k t n i
• Th c thi câu l nh, x lý d li u tr v
• ó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:
- 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
2. Hư ng d n th c hành Winforms v i C# Chương 5: ADO.NET
Hue-Aptech | Tr n Văn Long – Email: tvlongsp@gmail.com Trang 2
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);
cmdNorth.Connection.Open();
// 3. Th c hi n l nh
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);
3. Hư ng d n th c hành Winforms v i C# Chương 5: ADO.NET
Hue-Aptech | Tr n Văn Long – Email: tvlongsp@gmail.com Trang 3
}
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;
4. Hư ng d n th c hành Winforms v i C# Chương 5: ADO.NET
Hue-Aptech | Tr n Văn Long – Email: tvlongsp@gmail.com Trang 4
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
5. Hư ng d n th c hành Winforms v i C# Chương 5: ADO.NET
Hue-Aptech | Tr n Văn Long – Email: tvlongsp@gmail.com Trang 5
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
o Thông tin khách hàng s hi n th ngay khi vào form Qu n lý
o Thêm m i: thêm m i 1 khách hàng vào CSDL
o C p nh t: Ch nh s a thông tin 1 khách hàng trong CSDL
o Xóa: Xóa thông tin m t khách hàng
6. Hư ng d n th c hành Winforms v i C# Chương 5: ADO.NET
Hue-Aptech | Tr n Văn Long – Email: tvlongsp@gmail.com Trang 6
Ph n 2. K t n i không thư ng xuyên (Disconnected Architecture)
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: T o i tư ng DataAdapter và các câu l nh th c thi trên d li u
Bư c 4: d li u vào DataSet
Bư c 5: Tương tác, x lý d li u trên DataSet
Bư c 6: Lưu vào CSDL
2. Ví d m u
7. Hư ng d n th c hành Winforms v i C# Chương 5: ADO.NET
Hue-Aptech | Tr n Văn Long – Email: tvlongsp@gmail.com Trang 7
public partial class Form1 : Form
{
private DataSet ds;
private SqlConnection objConn;
private SqlDataAdapter objDa;
private string STRCONN = "Server=.;Database=BMS;uid=sa;pwd=;";
public Form1()
{
InitializeComponent();
}
private void loadData()
{
objConn = new SqlConnection(STRCONN);
ds = new DataSet();
objDa = new SqlDataAdapter("SELECT * FROM Books", objConn);
//T o các câu l nh Insert, Update, Delete t ng
SqlCommandBuilder cmb = new SqlCommandBuilder(objDa);
objDa.Fill(ds, "Books");
//Do du lieu len DataGridView
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Books";
//Bind du lieu len TextBox
txtID.DataBindings.Add("Text", ds, "Books.BookID");
txtTypeID.DataBindings.Add("Text", ds, "Books.TypeID");
txtTitle.DataBindings.Add("Text", ds, "Books.Title");
txtPublisher.DataBindings.Add("Text", ds, "Books.Publisher");
txtAuthor.DataBindings.Add("Text", ds, "Books.Author");
txtPrice.DataBindings.Add("Text", ds, "Books.Price");
}
private void Form1_Load(object sender, EventArgs e)
{
loadData();
}
private void cmdDelete_Click(object sender, EventArgs e)
{
int i = (int)this.BindingContext[ds, "Books"].Position;
ds.Tables[0].Rows[i].Delete();
objDa.Update(ds, "Books");
}
private void cmdAddNew_Click(object sender, EventArgs e)
{
txtID.Enabled = true;
txtTypeID.Enabled = true;
txtTitle.Enabled = true;
txtAuthor.Enabled = true;
txtPublisher.Enabled = true;
txtPrice.Enabled = true;
this.BindingContext[ds, "Books"].AddNew();
}
private void cmdUpdate_Click(object sender, EventArgs e)
{
//txtID.Enabled = true;
txtTypeID.Enabled = true;
8. Hư ng d n th c hành Winforms v i C# Chương 5: ADO.NET
Hue-Aptech | Tr n Văn Long – Email: tvlongsp@gmail.com Trang 8
txtTitle.Enabled = true;
txtAuthor.Enabled = true;
txtPublisher.Enabled = true;
txtPrice.Enabled = true;
}
private void cmdSave_Click(object sender, EventArgs e)
{
objDa.Update(ds,"Books");
}
}
3. M t s o n code m u
// Get current Rowposition
CurrencyManager cm = (CurrencyManager)this.BindingContext[ds,"Books"];
long rowPosition = (long)cm.Position;
// Combobox Databinding
cboTypeID.DataSource = ds;
cboTypeID.DisplayMember = "Books.TypeName";
cboTypeID.ValueMember = "Books.TypeID";
// Position to prev Record in Customer
private void btnPrev_Click(object sender, System.EventArgs e)
{
if (this.BindingContext[ds,"Books"].Position > 0)
{
this.BindingContext[ds,"Books"].Position--;
}
}
// Position to next Record in Customer
private void btnNext_Click(object sender, System.EventArgs e)
{
CurrencyManager cm = (CurrencyManager)this.BindingContext[ds,"Books"];
if (cm.Position < cm.Count - 1)
{
cm.Position++;
}
}
4. Bài t p
S d ng Disconnected Architecture làm l i bài t p Ph n 1