47
Bài 6: LẬP TRÌNH VỚI CSDL KIẾN TRÚC KẾT NỐI & BUỘC DỮ LIỆU

Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Embed Size (px)

DESCRIPTION

Thao tác sử dụng kiến trúc kết nối SqlCommand SqlDataReader BindingSource Điều hướng dữ liệu Lọc dữ liệu File config

Citation preview

Page 1: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Bài 6:LẬP TRÌNH VỚI CSDL

KIẾN TRÚC KẾT NỐI & BUỘC DỮ LIỆU

Page 2: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Giới thiệu về ADO.NETCác thành phần của ADO.NET

DataProviderDataSet

Các loại DataProviderSql Data Provider

SqlConnectionSqlDataAdapter

Hệ thống bài cũ

Giới thiệu về ADO.NETCác thành phần của ADO.NET

DataProviderDataSet

Các loại DataProviderSql Data Provider

SqlConnectionSqlDataAdapter

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 2

Page 3: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Mục tiêu bài học

Thao tác sử dụng kiến trúc kết nốiSqlCommandSqlDataReader

BindingSourceĐiều hướng dữ liệuLọc dữ liệu

File config

Thao tác sử dụng kiến trúc kết nốiSqlCommandSqlDataReader

BindingSourceĐiều hướng dữ liệuLọc dữ liệu

File config

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 3

Page 4: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

THAO TÁC VỚI DỮLIỆU BẰNG KIẾNTRÚC KẾT NỐI

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 4

THAO TÁC VỚI DỮLIỆU BẰNG KIẾNTRÚC KẾT NỐI

Page 5: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Kiến trúc kết nốiỨng dụng kết nối với CSDL và giữ kết nối cho đến khiđược đóng

Ưu điểm: Đọc dữ liệu nhanh chóng vì kết nối trực tiếp vớiCSDLNhược điểm: Ứng dụng vẫn kết nối với CSDL ngay cả khikhông thực hiện thao tác nào với CSDL lãng phí tàinguyên Server quá tải

Kiến trúc kết nối

Kiến trúc kết nốiỨng dụng kết nối với CSDL và giữ kết nối cho đến khiđược đóng

Ưu điểm: Đọc dữ liệu nhanh chóng vì kết nối trực tiếp vớiCSDLNhược điểm: Ứng dụng vẫn kết nối với CSDL ngay cả khikhông thực hiện thao tác nào với CSDL lãng phí tàinguyên Server quá tải

Lập trình với CSDL - ADO.Net & Kiến trúc không kết nối 5

Page 6: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Truy vấn CSDLCommand kết nối với CSDL thông qua Connection, sau đóCommand thực thi lệnh select và trả về kết quả làDataReader chứa các bản ghi.Ứng dụng sử dụng DataReader để đọc bản ghi này

Kiến trúc kết nối

Truy vấn CSDLCommand kết nối với CSDL thông qua Connection, sau đóCommand thực thi lệnh select và trả về kết quả làDataReader chứa các bản ghi.Ứng dụng sử dụng DataReader để đọc bản ghi này

Lập trình với CSDL - ADO.Net & Kiến trúc không kết nối 6

Page 7: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Thay đổi CSDLCommand kết nối với CSDL thông qua đối tượngConnection và thực thi các lệnh SQL trực tiếp trên CSDL(lệnh insert, delete…)

Kiến trúc kết nối

Lập trình với CSDL - ADO.Net & Kiến trúc không kết nối 7

Page 8: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Thực thi các câu lệnh sql trên CSDL được kết nối đếnHỗ trợ kiến trúc kết nốiPhương thức khởi tạo

Thuộc tính

SqlCommand

new SqlCommand()new SqlCommand(lệnh-sql)New SqlCommand(lệnh-sql, Connection)

Thực thi các câu lệnh sql trên CSDL được kết nối đếnHỗ trợ kiến trúc kết nốiPhương thức khởi tạo

Thuộc tính

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 8

new SqlCommand()new SqlCommand(lệnh-sql)New SqlCommand(lệnh-sql, Connection)

Thuộc tính Mô tảConnection Đối tượng Connection được sử dụng để kết nối với

CSDL

CommandText Lệnh Sql hoặc tên của stored procedure

CommandType Tên của kiểu liệt kê CommandType sẽ xác định giá trị củaCommandText được biên dịch như thế nào

Parameters Chứa một collection các tham số cho lệnh

Page 9: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Thực thi các câu lệnh sql trên CSDL được kết nối đếnHỗ trợ kiến trúc kết nốiPhương thức khởi tạo

Thuộc tính

SqlCommand

new SqlCommand()new SqlCommand(lệnh-sql)New SqlCommand(lệnh-sql, Connection)

Thực thi các câu lệnh sql trên CSDL được kết nối đếnHỗ trợ kiến trúc kết nốiPhương thức khởi tạo

Thuộc tính

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 9

new SqlCommand()new SqlCommand(lệnh-sql)New SqlCommand(lệnh-sql, Connection)

Thuộc tính Mô tảConnection Đối tượng Connection được sử dụng để kết nối với

CSDL

CommandText Lệnh Sql hoặc tên của stored procedure

CommandType Tên của kiểu liệt kê CommandType sẽ xác định giá trị củaCommandText được biên dịch như thế nào

Parameters Chứa một collection các tham số cho lệnh

Page 10: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Phương thức

Kiểu liệt kê CommandType

SqlCommand

Phương thức Mô tảExecuteReader() Thực thi truy vấn trong CommandText và trả về kết quả

là SqlDataReader

ExecuteNoneQuery() Thực thi lệnh sql được chỉ ra trong CommandText và trảvề số dòng mà lệnh này thao tác

ExecuteScalar() Thực thi truy vấn được chỉ ra trong CommandText và trảvề cột đầu tiên của dòng đầu tiên của tập kết quả

Phương thức

Kiểu liệt kê CommandType

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 10

ExecuteScalar() Thực thi truy vấn được chỉ ra trong CommandText và trảvề cột đầu tiên của dòng đầu tiên của tập kết quả

Thành viên Mô tảText CommandText chứa lệnh sql (mặc định)

StoredProcedure CommandText chứa tên của stored procedure

TableDirect CommandText chứa tên của bảng

Page 11: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Thao tác thêm một bản ghi vào bảng1 Khai báo các biến

SqlConnection conn;SqlCommand cmd;

2. Khởi tạo chuỗi kết nốiconn = new SqlConnection("Data Source=localhost;Initial Catalog=ProductDB;Persist Security Info=True;User

ID=sa;Password=sa");

conn.Open();

3. Khai báo câu lệnh truy vấnString sql = "insert into products values ('B0126','Lap trinh windows',100000,16)";

4. khởi tạo đối tượng SqlcommandSqlCommand cmd = new SqlCommand(sql, conn);

5. Thực thi câu lệnh truy vấncmd.ExecuteNonQuery();

6. Có thể đóng kết nốiconn.close();

Lập trình với CSDL - ADO.Net & Kiến trúc không kết nối

1 Khai báo các biếnSqlConnection conn;SqlCommand cmd;

2. Khởi tạo chuỗi kết nốiconn = new SqlConnection("Data Source=localhost;Initial Catalog=ProductDB;Persist Security Info=True;User

ID=sa;Password=sa");

conn.Open();

3. Khai báo câu lệnh truy vấnString sql = "insert into products values ('B0126','Lap trinh windows',100000,16)";

4. khởi tạo đối tượng SqlcommandSqlCommand cmd = new SqlCommand(sql, conn);

5. Thực thi câu lệnh truy vấncmd.ExecuteNonQuery();

6. Có thể đóng kết nốiconn.close();

11

Page 12: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Demo thao tác thêm một bản ghi vào bảng

private void btnAddNew_Click(object sender, EventArgs e)

{conn = new SqlConnection("Data Source=localhost;Initial Catalog=ProductDB;Persist Security

Info=True;User ID=sa;Password=sa");conn.Open();String sql = "insert into products values ('" + txtCode.Text + "','" + txtTitle.Text + "'," +System.Convert.ToInt32(txtPrice.Text) + "," + System.Convert.ToInt32(txtQuantity.Text) + ")";SqlCommand cmd = new SqlCommand(sql, conn);cmd.ExecuteNonQuery();

}

Lập trình với CSDL - ADO.Net & Kiến trúc không kết nối

private void btnAddNew_Click(object sender, EventArgs e)

{conn = new SqlConnection("Data Source=localhost;Initial Catalog=ProductDB;Persist Security

Info=True;User ID=sa;Password=sa");conn.Open();String sql = "insert into products values ('" + txtCode.Text + "','" + txtTitle.Text + "'," +System.Convert.ToInt32(txtPrice.Text) + "," + System.Convert.ToInt32(txtQuantity.Text) + ")";SqlCommand cmd = new SqlCommand(sql, conn);cmd.ExecuteNonQuery();

}

12

Page 13: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Thao tác sửa bản ghi1 Khai báo các biến

SqlConnection conn;SqlCommand cmd;

2. Khởi tạo chuỗi kết nốiconn = new SqlConnection("Data Source=localhost;Initial Catalog=ProductDB;Persist Security Info=True;User

ID=sa;Password=sa");

conn.Open();

3. Khai báo câu lệnh truy vấnString sql = "Update products set Description='Sach PHP-Nang cao', UnitPrice=56000,

OnHandQuantity=20 where ProductCode= 'S126' ";

4. khởi tạo đối tượng SqlcommandSqlCommand cmd = new SqlCommand(sql, conn);

5. Thực thi câu lệnh truy vấncmd.ExecuteNonQuery();

6. Có thể đóng kết nốiconn.close();

Lập trình với CSDL - ADO.Net & Kiến trúc không kết nối

1 Khai báo các biếnSqlConnection conn;SqlCommand cmd;

2. Khởi tạo chuỗi kết nốiconn = new SqlConnection("Data Source=localhost;Initial Catalog=ProductDB;Persist Security Info=True;User

ID=sa;Password=sa");

conn.Open();

3. Khai báo câu lệnh truy vấnString sql = "Update products set Description='Sach PHP-Nang cao', UnitPrice=56000,

OnHandQuantity=20 where ProductCode= 'S126' ";

4. khởi tạo đối tượng SqlcommandSqlCommand cmd = new SqlCommand(sql, conn);

5. Thực thi câu lệnh truy vấncmd.ExecuteNonQuery();

6. Có thể đóng kết nốiconn.close();

13

Page 14: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Thao tác sửa bản ghi

private void btnEdit_Click(object sender, EventArgs e){

conn = new SqlConnection("Data Source=localhost;Initial Catalog=ProductDB;Persist Security Info=True;UserID=sa;Password=sa");

conn.Open();String sql = "update products set Description='" + txtTitle.Text + "', UnitPrice=" +

System.Convert.ToInt32(txtPrice.Text) + ", OnHandQuantity=" + System.Convert.ToInt32(txtQuantity.Text) + " whereProductCode='"+txtCode.Text+"'" ;SqlCommand cmd = new SqlCommand(sql, conn);

cmd.ExecuteNonQuery();//conn.Close();

}

Lập trình với CSDL - ADO.Net & Kiến trúc không kết nối

private void btnEdit_Click(object sender, EventArgs e){

conn = new SqlConnection("Data Source=localhost;Initial Catalog=ProductDB;Persist Security Info=True;UserID=sa;Password=sa");

conn.Open();String sql = "update products set Description='" + txtTitle.Text + "', UnitPrice=" +

System.Convert.ToInt32(txtPrice.Text) + ", OnHandQuantity=" + System.Convert.ToInt32(txtQuantity.Text) + " whereProductCode='"+txtCode.Text+"'" ;SqlCommand cmd = new SqlCommand(sql, conn);

cmd.ExecuteNonQuery();//conn.Close();

}

14

Page 15: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Thao tác Xóa bản ghi1 Khai báo các biến

SqlConnection conn;SqlCommand cmd;

2. Khởi tạo chuỗi kết nốiconn = new SqlConnection("Data Source=localhost;Initial Catalog=ProductDB;Persist Security Info=True;User

ID=sa;Password=sa");

conn.Open();

3. Khai báo câu lệnh truy vấn // Xóa sách có Mã là S126

String sql = "Delete from products where ProductCode= 'S126' ";

4. khởi tạo đối tượng SqlcommandSqlCommand cmd = new SqlCommand(sql, conn);

5. Thực thi câu lệnh truy vấncmd.ExecuteNonQuery();

6. Có thể đóng kết nốiconn.close();

Lập trình với CSDL - ADO.Net & Kiến trúc không kết nối

1 Khai báo các biếnSqlConnection conn;SqlCommand cmd;

2. Khởi tạo chuỗi kết nốiconn = new SqlConnection("Data Source=localhost;Initial Catalog=ProductDB;Persist Security Info=True;User

ID=sa;Password=sa");

conn.Open();

3. Khai báo câu lệnh truy vấn // Xóa sách có Mã là S126

String sql = "Delete from products where ProductCode= 'S126' ";

4. khởi tạo đối tượng SqlcommandSqlCommand cmd = new SqlCommand(sql, conn);

5. Thực thi câu lệnh truy vấncmd.ExecuteNonQuery();

6. Có thể đóng kết nốiconn.close();

15

Page 16: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Sử dụng ExecuteReader() khi muốn lấy dữ liệu từ CSDL

Sử dụng ExecuteNoneQuery() khi thực thi lệnh khôngtruy vấn lên CSDL

Sử dụng ExecuteScalar() khi thực thi lệnh tích hợp

Demo sử dụng SqlCommand

string selectStatement = ("SELECT * FROM Customers ");SqlCommand selectCommand =

new SqlCommand(selectStatement, connection);SqlDataReader custReader= selectCommand.ExecuteReader();

string deleteStatement = ("DELETE * FROM Customers ");SqlCommand deleteCommand =

new SqlCommand(deleteStatement, connection);SqlDataReader custReader= deleteCommand.ExecuteNoneQuery();

Sử dụng ExecuteReader() khi muốn lấy dữ liệu từ CSDL

Sử dụng ExecuteNoneQuery() khi thực thi lệnh khôngtruy vấn lên CSDL

Sử dụng ExecuteScalar() khi thực thi lệnh tích hợp

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 16

string deleteStatement = ("DELETE * FROM Customers ");SqlCommand deleteCommand =

new SqlCommand(deleteStatement, connection);SqlDataReader custReader= deleteCommand.ExecuteNoneQuery();

string sumStatement = ("SELECT SUM(InvoiceTotal) FROM Invoices");SqlCommand sumCommand =

new SqlCommand(sumStatement, connection);int sum= (int)sumCommand.ExecuteScalar();

Page 17: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

SqlParameter chứa tham số cho SqlCommandPhương thức khởi tạo

Thuộc tính

SqlParameter

new SqlParameter()new SqlParameter(tên, giá-trị)

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 17

Thuộc tính Mô tảParameterName Tên của tham sốValue Giá trị của tham số

Page 18: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Tạo tham số

Thêm tham số vào Sql Command

Demo tạo tham sốvà thêm tham số và SqlCommand

SqlParameter customerIdParm = new SqlParameter();customerIdParm.ParameterName = "@CustomerId";customerIdParm.Value = customerId;

// hoặc

SqlParameter customerIdParm2 = new SqlParameter("@CustomerId", customerID);

Tạo tham số

Thêm tham số vào Sql Command

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 18

SqlParameter customerIdParm = new SqlParameter();customerIdParm.ParameterName = "@CustomerId";customerIdParm.Value = customerId;

// hoặc

SqlParameter customerIdParm2 = new SqlParameter("@CustomerId", customerID);

selectCommand.Parameters.Add(custemerIdParm);

Page 19: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

DataReader đọc tuần tự từng dòng từ luồng dữ liệucủa CSDLTăng hiệu suất bởi đọc tuần tự từng dòng nhưng tốn tàinguyên vì hỗ trợ kiến trúc kết nốiTạo SqlDataReader

Indexer/Thuộc tính/Phương thức

SqlDataReader

sqlCommand.ExecuteReader()

DataReader đọc tuần tự từng dòng từ luồng dữ liệucủa CSDLTăng hiệu suất bởi đọc tuần tự từng dòng nhưng tốn tàinguyên vì hỗ trợ kiến trúc kết nốiTạo SqlDataReader

Indexer/Thuộc tính/Phương thức

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 19

sqlCommand.ExecuteReader()

Indexer/Thuộc tính/Phương thức Mô tả[tên-cột] Lấy giá trị của cột có tên được chỉ ra

[index] Lấy giá trị của cột tại vị trí được chỉ ra

isClosed Cho biết data reader đã đóng chưa

Close() Đóng data reader

Read() Lấy giá trị tiếp theo và trả về giá trị Booleancho biết đã kết thúc data reader hay chưa

Page 20: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Thứ tự làm việc với SqlDataReader

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 20

Page 21: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Đưa dữ liệu từ DataReader vào Listview

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 21

Page 22: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Chức năng tìm kiếm theo mã sách

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 22

Sau khi tìm thấy dữ liệu được gán chocác TextBox

Page 23: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

BINDINGSOURCE

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 23

BINDINGSOURCE

Page 24: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Đối tượng BindingSource là cầu nối giữa CSDL và cácđiều khiển trên formBindingSource chứa nguồn dữ liệu liên kết với điềukhiểnCung cấp nhiều phương thức vào thuộc tính để điềuhướng và lọc dữ liệu dễ dàng

Binding Source

Đối tượng BindingSource là cầu nối giữa CSDL và cácđiều khiển trên formBindingSource chứa nguồn dữ liệu liên kết với điềukhiểnCung cấp nhiều phương thức vào thuộc tính để điềuhướng và lọc dữ liệu dễ dàng

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 24

Điều khiểntrên form

BindingSource

Page 25: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Thuộc tính

Phương thức

Binding Source

Thuộc tính Mô tảPosition Vị trí dòng hiện tại của nguồn dữ liệu

Count Số dòng trong nguồn dữ liệu

Filter Thiết lập bộ lọc

Phương thức Mô tả

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 25

Phương thức Mô tảAddNew() Thêm một dòng không có dữ liệu vào nguồn dữ liệu

EndEdit() Lưu thay đổi của dòng hiện tại

CancelEdit() Bỏ qua thay đổi của dòng hiện tại

RemoveCurrent() Xóa dòng hiện tại của nguồn dữ liệu

MoveFirst() Chuyển đến dòng đầu tiên của nguồn dữ liệu

MovePrevious() Chuyển đến dòng trước đó

MoveNext() Chuyển đến dòng tiếp theo

Page 26: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Buộc dữ liệu bằng BindingSource

Demo sử dụng BindingSource

conn = new SqlConnection(“chuỗi-kết-nối");daCustomers = new SqlDataAdapter

("Select CustomerID, Name, City, State from Customers", conn);ds = new DataSet();daCustomers.Fill(ds, "customers");

bs = new BindingSource();bs.DataSource = ds.Tables["customers"];

dgvCusotmers.DataSource = bs;

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 26

conn = new SqlConnection(“chuỗi-kết-nối");daCustomers = new SqlDataAdapter

("Select CustomerID, Name, City, State from Customers", conn);ds = new DataSet();daCustomers.Fill(ds, "customers");

bs = new BindingSource();bs.DataSource = ds.Tables["customers"];

dgvCusotmers.DataSource = bs;

Page 27: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Xử lý sự kiện cho button >> (chuyển đến bản ghi cuốicùng)

Demo sử dụng BindingSource

private void btnLast_Click(object sender, EventArgs e){

bs.MoveLast();}

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 27

Page 28: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Demo sử dụngBindingSource để lọc dữ liệu

private void cmbProductCode_SelectedIndexChanged(object sender, EventArgs e){

string stateCode = cmbStateCode.SelectedValue.ToString();if (stateCode != "" && stateCode !="System.Data.DataRowView"){

bs.Filter = "Bang = '" + stateCode + "'";}dgvCustomers.DataSource = bs;

}

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 28

private void cmbProductCode_SelectedIndexChanged(object sender, EventArgs e){

string stateCode = cmbStateCode.SelectedValue.ToString();if (stateCode != "" && stateCode !="System.Data.DataRowView"){

bs.Filter = "Bang = '" + stateCode + "'";}dgvCustomers.DataSource = bs;

}

Chỉ hiển thị khách hàngở bang được chọn trên

ComboBox

Page 29: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

FILE CONFIG

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 29

FILE CONFIG

Page 30: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Mỗi lần kết nối lại phải gõ vào chuỗi kết nối Khi thay đổi CSDL phải sửa nhiều lần

Để thống nhất, Visual Sutudio cho phép lưu chuỗi kết nốivào file config và cung cấp các lớp để đọc chuỗi kết nốitừ file config Chuỗi kết nối chỉ được lưu một nơi duy nhất trên fileconfig

File app.config

Mỗi lần kết nối lại phải gõ vào chuỗi kết nối Khi thay đổi CSDL phải sửa nhiều lần

Để thống nhất, Visual Sutudio cho phép lưu chuỗi kết nốivào file config và cung cấp các lớp để đọc chuỗi kết nốitừ file config Chuỗi kết nối chỉ được lưu một nơi duy nhất trên fileconfig

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 30

Page 31: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

B1. Tạo file configChọn project Add New ItemChọn mục Application Configuration File

Demo lưu và lấychuỗi kết nối từ file config

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 31

Page 32: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

B2. Thêm chuỗi kết nối vào file config

Demo lưu và lấychuỗi kết nối từ file config

<?xml version="1.0" encoding="utf-8" ?><configuration><connectionStrings>

<add name=“ProductDBConnectionString"connectionString="Data Source=SAMSUNG-R439;Initial Catalog=ProductDB;User

ID=sa;Password=123456"providerName="System.Data.SqlClient" />

</connectionStrings></configuration>

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 32

<?xml version="1.0" encoding="utf-8" ?><configuration><connectionStrings>

<add name=“ProductDBConnectionString"connectionString="Data Source=SAMSUNG-R439;Initial Catalog=ProductDB;User

ID=sa;Password=123456"providerName="System.Data.SqlClient" />

</connectionStrings></configuration>

Page 33: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

B3. Lấy chuỗi kết nốiLưu ý: để sửa dụng được lớp ConfigurationManager phảiadd thêm assembly này vàoVào Project Add Reference… chọnSystem.Configuration

Demo lưu và lấychuỗi kết nối từ file config

string connectionString = ConfigurationManager.ConnectionStrings["ProductDBConnectionString"].ToString();

SqlConnection conn = new SqlConnection(connectionString);

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 33

string connectionString = ConfigurationManager.ConnectionStrings["ProductDBConnectionString"].ToString();

SqlConnection conn = new SqlConnection(connectionString);

Page 34: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

xử lý sự kiện với môhình 3 tầng

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 34

Page 35: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Demo đọc dữ liệu từ SqlDataReader

connection.Open();SqlDataReader custReader =

selectCommand.ExecuteReader(CommandBehavior.SingleRow);if (custReader.Read()){

Customer customer = new Customer();customer.CustomerID = (int)custReader["CustomerID"];customer.Name = custReader["Name"].ToString();customer.Address = custReader["Address"].ToString();customer.City = custReader["City"].ToString();customer.State = custReader["State"].ToString();customer.ZipCode = custReader["ZipCode"].ToString();return customer;

}connection.Close();

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 35

connection.Open();SqlDataReader custReader =

selectCommand.ExecuteReader(CommandBehavior.SingleRow);if (custReader.Read()){

Customer customer = new Customer();customer.CustomerID = (int)custReader["CustomerID"];customer.Name = custReader["Name"].ToString();customer.Address = custReader["Address"].ToString();customer.City = custReader["City"].ToString();customer.State = custReader["State"].ToString();customer.ZipCode = custReader["ZipCode"].ToString();return customer;

}connection.Close();

Đóng và mở Connection khi thao tác với Command để thực thi lệnh Sql

Page 36: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Sử dụng phương thức ExecuteReader củaSqlCommand để lấy dữ liệuSử dụng SqlDataReader để đọc dữ liệu vào formSử dụng phương thức ExecuteNoneQuery củaSqlCommand để thêm, sửa, xóa dữ liệu

Demo thao tác vớidữ liệu bằng kiến trúc kết nối

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 36

Page 37: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Demo ứng dụng Customer Maintenance

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 37

Page 38: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Demo xử lý sự kiện Button GetCustomerprivate void btnGetCustomer_Click(object sender, EventArgs e){

int customerID = Convert.ToInt32(txtCustomerID.Text);//Tạo kết nốiSqlConnection connection = new SqlConnection ("chuỗi-kết-nối");//Tạo commandstring selectStatement

= "SELECT CustomerID, Name, Address, City, State, ZipCode "+ "FROM Customers WHERE CustomerID = @CustomerID";

SqlCommand selectCommand =new SqlCommand(selectStatement, connection);

selectCommand.Parameters.AddWithValue("@CustomerID", customerID);//Đọc dữ liệu và gán cho các trườngconnection.Open();SqlDataReader custReader = selectCommand.ExecuteReader();if (custReader.Read()){

txtName.Text = custReader["Name"].ToString();…

}connection.Close();

}

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 38

private void btnGetCustomer_Click(object sender, EventArgs e){

int customerID = Convert.ToInt32(txtCustomerID.Text);//Tạo kết nốiSqlConnection connection = new SqlConnection ("chuỗi-kết-nối");//Tạo commandstring selectStatement

= "SELECT CustomerID, Name, Address, City, State, ZipCode "+ "FROM Customers WHERE CustomerID = @CustomerID";

SqlCommand selectCommand =new SqlCommand(selectStatement, connection);

selectCommand.Parameters.AddWithValue("@CustomerID", customerID);//Đọc dữ liệu và gán cho các trườngconnection.Open();SqlDataReader custReader = selectCommand.ExecuteReader();if (custReader.Read()){

txtName.Text = custReader["Name"].ToString();…

}connection.Close();

}

Page 39: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Demo xử lý sự kiện trênAccept trên form Add Customer

private void btnAccept_Click(object sender, EventArgs e){

string name = txtName.Text;string address = txtAddress.Text;string city = txtCity.Text;string state = cboStates.SelectedValue.ToString();string zipCode = txtZipCode.Text;

SqlConnection connection = MMABooksDB.GetConnection();string insertStatement =

"INSERT Customers " +"(Name, Address, City, State, ZipCode) " +"VALUES ('"+name+"','"+ address+"','"+city+"','"+state+"','"+zipCode+"')";

SqlCommand insertCommand =new SqlCommand(insertStatement, connection);

connection.Open();insertCommand.ExecuteNonQuery();connection.Close();

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 39

private void btnAccept_Click(object sender, EventArgs e){

string name = txtName.Text;string address = txtAddress.Text;string city = txtCity.Text;string state = cboStates.SelectedValue.ToString();string zipCode = txtZipCode.Text;

SqlConnection connection = MMABooksDB.GetConnection();string insertStatement =

"INSERT Customers " +"(Name, Address, City, State, ZipCode) " +"VALUES ('"+name+"','"+ address+"','"+city+"','"+state+"','"+zipCode+"')";

SqlCommand insertCommand =new SqlCommand(insertStatement, connection);

connection.Open();insertCommand.ExecuteNonQuery();connection.Close();

Page 40: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Ứng dụng được tổ chức theo mô hình 3 tầng như sau:Tầng hiển thị: FormTầng xử lý nghiệp vụ: Customer, StateTầng CSDL: CustomerDB, MMABookDB, StateDB

Tổ chức ứng dụng

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 40

Page 41: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

frmCustomer gọi đến lớp CustomerDB để thao tác vớiCSDLDữ liệu được truyền giữa CustomerDB và frmCustomerthông qua lớp Customer

Demo viết xử lý sự kiệnGetCustomer với mô hình 3 tầng

frmCustomer

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 41

frmCustomer

Customer

CustomerDB MMABookDB

Page 42: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Demo viết mã cho lớp Customer

public class Customer{

public Customer() { }

public int CustomerID { get; set; }

public string Name { get; set; }

public string Address { get; set; }

public string City { get; set; }

public string State { get; set; }

public string ZipCode { get; set; }}

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 42

public class Customer{

public Customer() { }

public int CustomerID { get; set; }

public string Name { get; set; }

public string Address { get; set; }

public string City { get; set; }

public string State { get; set; }

public string ZipCode { get; set; }}

Page 43: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Demo viết mã cho lớp MMABooksDB

public static class MMABooksDB{

public static SqlConnection GetConnection(){

string connectionString = "chuỗi kết nối";SqlConnection connection = new SqlConnection(connectionString);connection.Open();return connection;

}}

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 43

public static class MMABooksDB{

public static SqlConnection GetConnection(){

string connectionString = "chuỗi kết nối";SqlConnection connection = new SqlConnection(connectionString);connection.Open();return connection;

}}

Page 44: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Demo viết phương thứcGetCustomer của lớp CustomerDB

public static Customer GetCustomer(int customerID){

SqlConnection connection = MMABooksDB.GetConnection();string selectStatement

= "SELECT CustomerID, Name, Address, City, State, ZipCode "+ "FROM Customers "+ "WHERE CustomerID = @CustomerID";

SqlCommand selectCommand =new SqlCommand(selectStatement, connection);

selectCommand.Parameters.AddWithValue("@CustomerID", customerID);

connection.Open();SqlDataReader custReader =

selectCommand.ExecuteReader(CommandBehavior.SingleRow);

Customer customer = new Customer();customer.CustomerID = Convert.ToInt32(custReader["CustomerID"].ToString());customer.Name = custReader["Name"].ToString();…connection.Close();return customer;

} Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 44

public static Customer GetCustomer(int customerID){

SqlConnection connection = MMABooksDB.GetConnection();string selectStatement

= "SELECT CustomerID, Name, Address, City, State, ZipCode "+ "FROM Customers "+ "WHERE CustomerID = @CustomerID";

SqlCommand selectCommand =new SqlCommand(selectStatement, connection);

selectCommand.Parameters.AddWithValue("@CustomerID", customerID);

connection.Open();SqlDataReader custReader =

selectCommand.ExecuteReader(CommandBehavior.SingleRow);

Customer customer = new Customer();customer.CustomerID = Convert.ToInt32(custReader["CustomerID"].ToString());customer.Name = custReader["Name"].ToString();…connection.Close();return customer;

}

Page 45: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Xử lý sự kiện choButton GetCustomer trên form

private void btnGetCustomer_Click(object sender, EventArgs e){

if (Validator.IsPresent(txtCustomerID) &&Validator.IsInt32(txtCustomerID))

{int customerID = Convert.ToInt32(txtCustomerID.Text);this.GetCustomer(customerID);if (customer == null){

MessageBox.Show("No customer found with this ID. " +"Please try again.", "Customer Not Found");

this.ClearControls();}else

this.DisplayCustomer();}

}

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 45

private void btnGetCustomer_Click(object sender, EventArgs e){

if (Validator.IsPresent(txtCustomerID) &&Validator.IsInt32(txtCustomerID))

{int customerID = Convert.ToInt32(txtCustomerID.Text);this.GetCustomer(customerID);if (customer == null){

MessageBox.Show("No customer found with this ID. " +"Please try again.", "Customer Not Found");

this.ClearControls();}else

this.DisplayCustomer();}

}

Page 46: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

Các đối tượng SqlConnection, SqlCommand,SqlDataReader thao tác với CSDL SQL server bằngkiến trúc kết nối. Trong đó SqlConnection kết nối vớiCSDL; SqlCommand lấy, thêm, sửa, xóa dữ liệu vàSqlDataReader đọc dữ liệuĐiều khiển buộc là điều khiển liên kết với dữ liệu trênCSDLThuộc tính DataSource của điều khiển buộc chỉ ranguồn dữ liệu cho điều khiển (thường là bảng trêndataset)

Tổng kết bài học

Các đối tượng SqlConnection, SqlCommand,SqlDataReader thao tác với CSDL SQL server bằngkiến trúc kết nối. Trong đó SqlConnection kết nối vớiCSDL; SqlCommand lấy, thêm, sửa, xóa dữ liệu vàSqlDataReader đọc dữ liệuĐiều khiển buộc là điều khiển liên kết với dữ liệu trênCSDLThuộc tính DataSource của điều khiển buộc chỉ ranguồn dữ liệu cho điều khiển (thường là bảng trêndataset)

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 46

Page 47: Bài 6: Lập trình với CSDL Kiến trúc kết nối & Buộc dữ liệu - Lập trình winform - Giáo trình FPT

BindingSource là cầu nối giữa CSDL và các điều khiểntrên formBindingSource chứa nguồn dữ liệu liên kết với điềukhiểnBindingSource cung cấp nhiều phương thức vào thuộctính để điều hướng và lọc dữ liệu dễ dàngĐể dễ dàng phát triển ứng dụng và bảo trì, ứng dụngkết nối với CSDL được tổ chức thành mô hình 3 tầng

Tổng kết bài học

BindingSource là cầu nối giữa CSDL và các điều khiểntrên formBindingSource chứa nguồn dữ liệu liên kết với điềukhiểnBindingSource cung cấp nhiều phương thức vào thuộctính để điều hướng và lọc dữ liệu dễ dàngĐể dễ dàng phát triển ứng dụng và bảo trì, ứng dụngkết nối với CSDL được tổ chức thành mô hình 3 tầng

Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 47