SlideShare a Scribd company logo
1 of 47
Download to read offline
Bài 6:
LẬP TRÌNH VỚI CSDL
KIẾN TRÚC KẾT NỐI & BUỘC DỮ LIỆU
Giới thiệu về ADO.NET
Các thành phần của ADO.NET
DataProvider
DataSet
Các loại DataProvider
Sql Data Provider
SqlConnection
SqlDataAdapter
Hệ thống bài cũ
Giới thiệu về ADO.NET
Các thành phần của ADO.NET
DataProvider
DataSet
Các loại DataProvider
Sql Data Provider
SqlConnection
SqlDataAdapter
Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 2
Mục tiêu bài học
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
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
Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 3
THAO TÁC VỚI DỮ
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 4
THAO TÁC VỚI DỮ
LIỆU BẰNG 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ới
CSDL
Nhược điểm: Ứng dụng vẫn kết nối với CSDL ngay cả khi
không thực hiện thao tác nào với CSDL  lãng phí tài
nguyê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ới
CSDL
Nhược điểm: Ứng dụng vẫn kết nối với CSDL ngay cả khi
không thực hiện thao tác nào với CSDL  lãng phí tài
nguyê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
Truy vấn CSDL
Command 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 CSDL
Command 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
Thay đổi CSDL
Command kết nối với CSDL thông qua đối tượng
Connection 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
Thực thi các câu lệnh sql trên CSDL được kết nối đến
Hỗ trợ kiến trúc kết nối
Phươ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 đến
Hỗ trợ kiến trúc kết nối
Phươ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ủa
CommandText được biên dịch như thế nào
Parameters Chứa một collection các tham số cho lệnh
Thực thi các câu lệnh sql trên CSDL được kết nối đến
Hỗ trợ kiến trúc kết nối
Phươ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 đến
Hỗ trợ kiến trúc kết nối
Phươ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ủa
CommandText được biên dịch như thế nào
Parameters Chứa một collection các tham số cho lệnh
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
Thao tác thêm một bản ghi vào bảng
1 Khai báo các biến
SqlConnection conn;
SqlCommand cmd;
2. Khởi tạo chuỗi kết nối
conn = 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
String sql = "insert into products values ('B0126','Lap trinh windows',100000,16)";
4. khởi tạo đối tượng Sqlcommand
SqlCommand cmd = new SqlCommand(sql, conn);
5. Thực thi câu lệnh truy vấn
cmd.ExecuteNonQuery();
6. Có thể đóng kết nối
conn.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ến
SqlConnection conn;
SqlCommand cmd;
2. Khởi tạo chuỗi kết nối
conn = 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
String sql = "insert into products values ('B0126','Lap trinh windows',100000,16)";
4. khởi tạo đối tượng Sqlcommand
SqlCommand cmd = new SqlCommand(sql, conn);
5. Thực thi câu lệnh truy vấn
cmd.ExecuteNonQuery();
6. Có thể đóng kết nối
conn.close();
11
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
Thao tác sửa bản ghi
1 Khai báo các biến
SqlConnection conn;
SqlCommand cmd;
2. Khởi tạo chuỗi kết nối
conn = 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
String sql = "Update products set Description='Sach PHP-Nang cao', UnitPrice=56000,
OnHandQuantity=20 where ProductCode= 'S126' ";
4. khởi tạo đối tượng Sqlcommand
SqlCommand cmd = new SqlCommand(sql, conn);
5. Thực thi câu lệnh truy vấn
cmd.ExecuteNonQuery();
6. Có thể đóng kết nối
conn.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ến
SqlConnection conn;
SqlCommand cmd;
2. Khởi tạo chuỗi kết nối
conn = 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
String sql = "Update products set Description='Sach PHP-Nang cao', UnitPrice=56000,
OnHandQuantity=20 where ProductCode= 'S126' ";
4. khởi tạo đối tượng Sqlcommand
SqlCommand cmd = new SqlCommand(sql, conn);
5. Thực thi câu lệnh truy vấn
cmd.ExecuteNonQuery();
6. Có thể đóng kết nối
conn.close();
13
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;User
ID=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) + " where
ProductCode='"+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;User
ID=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) + " where
ProductCode='"+txtCode.Text+"'" ;
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
//conn.Close();
}
14
Thao tác Xóa bản ghi
1 Khai báo các biến
SqlConnection conn;
SqlCommand cmd;
2. Khởi tạo chuỗi kết nối
conn = 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 Sqlcommand
SqlCommand cmd = new SqlCommand(sql, conn);
5. Thực thi câu lệnh truy vấn
cmd.ExecuteNonQuery();
6. Có thể đóng kết nối
conn.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ến
SqlConnection conn;
SqlCommand cmd;
2. Khởi tạo chuỗi kết nối
conn = 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 Sqlcommand
SqlCommand cmd = new SqlCommand(sql, conn);
5. Thực thi câu lệnh truy vấn
cmd.ExecuteNonQuery();
6. Có thể đóng kết nối
conn.close();
15
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ông
truy 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ông
truy 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();
SqlParameter chứa tham số cho SqlCommand
Phươ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ố
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);
DataReader đọc tuần tự từng dòng từ luồng dữ liệu
của CSDL
Tăng hiệu suất bởi đọc tuần tự từng dòng nhưng tốn tài
nguyên vì hỗ trợ kiến trúc kết nối
Tạ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ệu
của CSDL
Tăng hiệu suất bởi đọc tuần tự từng dòng nhưng tốn tài
nguyên vì hỗ trợ kiến trúc kết nối
Tạ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ị Boolean
cho biết đã kết thúc data reader hay chưa
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
Đư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
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 cho
các TextBox
BINDINGSOURCE
Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 23
BINDINGSOURCE
Đối tượng BindingSource là cầu nối giữa CSDL và các
điều khiển trên form
BindingSource chứa nguồn dữ liệu liên kết với điều
khiển
Cung cấp nhiều phương thức vào thuộc tính để điều
hướ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 form
BindingSource chứa nguồn dữ liệu liên kết với điều
khiển
Cung cấp nhiều phương thức vào thuộc tính để điều
hướ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ển
trên form
BindingSource
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
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;
Xử lý sự kiện cho button >> (chuyển đến bản ghi cuối
cù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
Demo sử dụng
BindingSource để 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
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
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ối
vào file config và cung cấp các lớp để đọc chuỗi kết nối
từ file config
 Chuỗi kết nối chỉ được lưu một nơi duy nhất trên file
config
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ối
vào file config và cung cấp các lớp để đọc chuỗi kết nối
từ file config
 Chuỗi kết nối chỉ được lưu một nơi duy nhất trên file
config
Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 30
B1. Tạo file config
Chọn project  Add  New Item
Chọn mục Application Configuration File
Demo lưu và lấy
chuỗ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
B2. Thêm chuỗi kết nối vào file config
Demo lưu và lấy
chuỗ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>
B3. Lấy chuỗi kết nối
Lưu ý: để sửa dụng được lớp ConfigurationManager phải
add thêm assembly này vào
Vào Project  Add Reference…  chọn
System.Configuration
Demo lưu và lấy
chuỗ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);
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
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
Sử dụng phương thức ExecuteReader của
SqlCommand để lấy dữ liệu
Sử dụng SqlDataReader để đọc dữ liệu vào form
Sử dụng phương thức ExecuteNoneQuery của
SqlCommand để thêm, sửa, xóa dữ liệu
Demo thao tác với
dữ 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
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
Demo xử lý sự kiện Button GetCustomer
private void btnGetCustomer_Click(object sender, EventArgs e)
{
int customerID = Convert.ToInt32(txtCustomerID.Text);
//Tạo kết nối
SqlConnection connection = new SqlConnection ("chuỗi-kết-nối");
//Tạo command
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);
//Đọc dữ liệu và gán cho các trường
connection.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ối
SqlConnection connection = new SqlConnection ("chuỗi-kết-nối");
//Tạo command
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);
//Đọc dữ liệu và gán cho các trường
connection.Open();
SqlDataReader custReader = selectCommand.ExecuteReader();
if (custReader.Read())
{
txtName.Text = custReader["Name"].ToString();
…
}
connection.Close();
}
Demo xử lý sự kiện trên
Accept 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();
Ứng dụng được tổ chức theo mô hình 3 tầng như sau:
Tầng hiển thị: Form
Tầng xử lý nghiệp vụ: Customer, State
Tầ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
frmCustomer gọi đến lớp CustomerDB để thao tác với
CSDL
Dữ liệu được truyền giữa CustomerDB và frmCustomer
thông qua lớp Customer
Demo viết xử lý sự kiện
GetCustomer 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
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; }
}
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;
}
}
Demo viết phương thức
GetCustomer 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;
}
Xử lý sự kiện cho
Button 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();
}
}
Các đối tượng SqlConnection, SqlCommand,
SqlDataReader thao tác với CSDL SQL server bằng
kiến trúc kết nối. Trong đó SqlConnection kết nối với
CSDL; 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ên
CSDL
Thuộc tính DataSource của điều khiển buộc chỉ ra
nguồn dữ liệu cho điều khiển (thường là bảng trên
dataset)
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ằng
kiến trúc kết nối. Trong đó SqlConnection kết nối với
CSDL; 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ên
CSDL
Thuộc tính DataSource của điều khiển buộc chỉ ra
nguồn dữ liệu cho điều khiển (thường là bảng trên
dataset)
Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 46
BindingSource là cầu nối giữa CSDL và các điều khiển
trên form
BindingSource chứa nguồn dữ liệu liên kết với điều
khiển
BindingSource cung cấp nhiều phương thức vào thuộc
tí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ụng
kế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ển
trên form
BindingSource chứa nguồn dữ liệu liên kết với điều
khiển
BindingSource cung cấp nhiều phương thức vào thuộc
tí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ụng
kế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

More Related Content

What's hot

6.adapterset
6.adapterset6.adapterset
6.adapterset
Dao Uit
 
00 overview of_sql_server
00 overview of_sql_server00 overview of_sql_server
00 overview of_sql_server
thai
 
Trong bài viết hôm nay
Trong bài viết hôm nayTrong bài viết hôm nay
Trong bài viết hôm nay
ledoanduc
 
Mvc4 seminar - hoclaptrinhweb.com - Tài liệu Nhất Nghệ
Mvc4 seminar - hoclaptrinhweb.com - Tài liệu Nhất NghệMvc4 seminar - hoclaptrinhweb.com - Tài liệu Nhất Nghệ
Mvc4 seminar - hoclaptrinhweb.com - Tài liệu Nhất Nghệ
MasterCode.vn
 

What's hot (20)

Bài 3: Lập trình giao diện điều khiển & Xử lý sự kiện - Lập trình winform - G...
Bài 3: Lập trình giao diện điều khiển & Xử lý sự kiện - Lập trình winform - G...Bài 3: Lập trình giao diện điều khiển & Xử lý sự kiện - Lập trình winform - G...
Bài 3: Lập trình giao diện điều khiển & Xử lý sự kiện - Lập trình winform - G...
 
Slides1
Slides1Slides1
Slides1
 
6.adapterset
6.adapterset6.adapterset
6.adapterset
 
Bài 5: Hàm người dùng định nghĩa & VIEW - Giáo trình FPT
Bài 5: Hàm người dùng định nghĩa & VIEW - Giáo trình FPTBài 5: Hàm người dùng định nghĩa & VIEW - Giáo trình FPT
Bài 5: Hàm người dùng định nghĩa & VIEW - Giáo trình FPT
 
Bài 6: Bảo mật trong SQL SERVER 2008 - Giáo trình FPT
Bài 6: Bảo mật trong SQL SERVER 2008 - Giáo trình FPTBài 6: Bảo mật trong SQL SERVER 2008 - Giáo trình FPT
Bài 6: Bảo mật trong SQL SERVER 2008 - Giáo trình FPT
 
Bài 6: Điều khiển DetailsView, FormView, ListView, DataPager
Bài 6: Điều khiển DetailsView, FormView, ListView, DataPagerBài 6: Điều khiển DetailsView, FormView, ListView, DataPager
Bài 6: Điều khiển DetailsView, FormView, ListView, DataPager
 
Bài 3: Ngôn ngữ truy vân có cấu trúc (SQL) - Giáo trình FPT
Bài 3: Ngôn ngữ truy vân có cấu trúc (SQL) - Giáo trình FPTBài 3: Ngôn ngữ truy vân có cấu trúc (SQL) - Giáo trình FPT
Bài 3: Ngôn ngữ truy vân có cấu trúc (SQL) - Giáo trình FPT
 
Sao lưu & phục hồi database SQL Server | zBackup.vn
Sao lưu & phục hồi database SQL Server | zBackup.vnSao lưu & phục hồi database SQL Server | zBackup.vn
Sao lưu & phục hồi database SQL Server | zBackup.vn
 
Bài 1: Làm quen với SQL Server 2008 - Giáo trình FPT
Bài 1: Làm quen với SQL Server 2008 - Giáo trình FPTBài 1: Làm quen với SQL Server 2008 - Giáo trình FPT
Bài 1: Làm quen với SQL Server 2008 - Giáo trình FPT
 
Chuong 07_ gắng kết dữ liệu asp.net
Chuong 07_ gắng kết dữ liệu asp.netChuong 07_ gắng kết dữ liệu asp.net
Chuong 07_ gắng kết dữ liệu asp.net
 
Bài 7: Thiết kế cơ sở dữ liệu vật lý
Bài 7: Thiết kế cơ sở dữ liệu vật lýBài 7: Thiết kế cơ sở dữ liệu vật lý
Bài 7: Thiết kế cơ sở dữ liệu vật lý
 
00 overview of_sql_server
00 overview of_sql_server00 overview of_sql_server
00 overview of_sql_server
 
Bài 1: Làm quen với ASP.NET - Giáo trình FPT - Có ví dụ kèm theo
Bài 1: Làm quen với ASP.NET - Giáo trình FPT - Có ví dụ kèm theoBài 1: Làm quen với ASP.NET - Giáo trình FPT - Có ví dụ kèm theo
Bài 1: Làm quen với ASP.NET - Giáo trình FPT - Có ví dụ kèm theo
 
Trong bài viết hôm nay
Trong bài viết hôm nayTrong bài viết hôm nay
Trong bài viết hôm nay
 
Hướng dẫn lập trình quản lý c#
Hướng dẫn lập trình quản lý c#Hướng dẫn lập trình quản lý c#
Hướng dẫn lập trình quản lý c#
 
Mvc4 seminar - hoclaptrinhweb.com - Tài liệu Nhất Nghệ
Mvc4 seminar - hoclaptrinhweb.com - Tài liệu Nhất NghệMvc4 seminar - hoclaptrinhweb.com - Tài liệu Nhất Nghệ
Mvc4 seminar - hoclaptrinhweb.com - Tài liệu Nhất Nghệ
 
Mô hình 3 lớp trong C#
Mô hình 3 lớp trong C#Mô hình 3 lớp trong C#
Mô hình 3 lớp trong C#
 
Bài 5: Chuẩn hóa cơ sở dữ liệu
Bài 5: Chuẩn hóa cơ sở dữ liệuBài 5: Chuẩn hóa cơ sở dữ liệu
Bài 5: Chuẩn hóa cơ sở dữ liệu
 
Slide Hệ Quản Trị Cơ sở dữ liệu - CHƯƠNG 5
Slide Hệ Quản Trị Cơ sở dữ liệu - CHƯƠNG 5Slide Hệ Quản Trị Cơ sở dữ liệu - CHƯƠNG 5
Slide Hệ Quản Trị Cơ sở dữ liệu - CHƯƠNG 5
 
BÀI 2: Thiết kế FORM và xử lý sự kiện - Giáo trình FPT
BÀI 2: Thiết kế FORM và xử lý sự kiện - Giáo trình FPTBÀI 2: Thiết kế FORM và xử lý sự kiện - Giáo trình FPT
BÀI 2: Thiết kế FORM và xử lý sự kiện - Giáo trình FPT
 

Viewers also liked

Viewers also liked (20)

BÀI 4 Nâng cao khả năng thiết kế web mobile với thành phần jquery mobile - Gi...
BÀI 4 Nâng cao khả năng thiết kế web mobile với thành phần jquery mobile - Gi...BÀI 4 Nâng cao khả năng thiết kế web mobile với thành phần jquery mobile - Gi...
BÀI 4 Nâng cao khả năng thiết kế web mobile với thành phần jquery mobile - Gi...
 
Bài 6: Tạo hiệu ứng và validate Form - Giáo trình FPT
Bài 6: Tạo hiệu ứng và validate Form - Giáo trình FPTBài 6: Tạo hiệu ứng và validate Form - Giáo trình FPT
Bài 6: Tạo hiệu ứng và validate Form - Giáo trình FPT
 
BÀI 4 Làm việc với các thành phần VIDEO, AUDIO, CANVAS của HTML5
BÀI 4 Làm việc với các thành phần VIDEO, AUDIO, CANVAS của HTML5BÀI 4 Làm việc với các thành phần VIDEO, AUDIO, CANVAS của HTML5
BÀI 4 Làm việc với các thành phần VIDEO, AUDIO, CANVAS của HTML5
 
Bài 7 Xây dựng website - Giáo trình FPT
Bài 7 Xây dựng website - Giáo trình FPTBài 7 Xây dựng website - Giáo trình FPT
Bài 7 Xây dựng website - Giáo trình FPT
 
Bài 13: Nâng cấp từ Windows Server 2003 lên Windows Server 2008 - Giáo trình FPT
Bài 13: Nâng cấp từ Windows Server 2003 lên Windows Server 2008 - Giáo trình FPTBài 13: Nâng cấp từ Windows Server 2003 lên Windows Server 2008 - Giáo trình FPT
Bài 13: Nâng cấp từ Windows Server 2003 lên Windows Server 2008 - Giáo trình FPT
 
BÀI 3 Thiết kế web cho di động với dreamweaver CS5 & Jquery - Giáo trình FPT
BÀI 3 Thiết kế web cho di động với dreamweaver CS5 & Jquery - Giáo trình FPTBÀI 3 Thiết kế web cho di động với dreamweaver CS5 & Jquery - Giáo trình FPT
BÀI 3 Thiết kế web cho di động với dreamweaver CS5 & Jquery - Giáo trình FPT
 
Bài 5 Bố cục trang cơ bản - Giáo trình FPT
Bài 5 Bố cục trang cơ bản - Giáo trình FPTBài 5 Bố cục trang cơ bản - Giáo trình FPT
Bài 5 Bố cục trang cơ bản - Giáo trình FPT
 
Bài 4 Định vị trí box - Giáo trình FPT
Bài 4 Định vị trí box - Giáo trình FPTBài 4 Định vị trí box - Giáo trình FPT
Bài 4 Định vị trí box - Giáo trình FPT
 
Bài 10: Giới thiệu về Server Core - Giáo trình FPT
Bài 10: Giới thiệu về Server Core - Giáo trình FPTBài 10: Giới thiệu về Server Core - Giáo trình FPT
Bài 10: Giới thiệu về Server Core - Giáo trình FPT
 
BÀI 2 Tìm hiểu ngôn ngữ đánh dấu trong việc phát triển web mobile - Giáo trìn...
BÀI 2 Tìm hiểu ngôn ngữ đánh dấu trong việc phát triển web mobile - Giáo trìn...BÀI 2 Tìm hiểu ngôn ngữ đánh dấu trong việc phát triển web mobile - Giáo trìn...
BÀI 2 Tìm hiểu ngôn ngữ đánh dấu trong việc phát triển web mobile - Giáo trìn...
 
BÀI 6 Làm việc với thành phần mở rộng của CSS3 - Giáo trình FPT
BÀI 6 Làm việc với thành phần mở rộng của CSS3 - Giáo trình FPTBÀI 6 Làm việc với thành phần mở rộng của CSS3 - Giáo trình FPT
BÀI 6 Làm việc với thành phần mở rộng của CSS3 - Giáo trình FPT
 
Bài 3 Tạo style cho font và văn bản - Giáo trình FPT
Bài 3 Tạo style cho font và văn bản - Giáo trình FPTBài 3 Tạo style cho font và văn bản - Giáo trình FPT
Bài 3 Tạo style cho font và văn bản - Giáo trình FPT
 
Bài 2 Cơ chế làm việc của CSS - Giáo trình FPT
Bài 2 Cơ chế làm việc của CSS - Giáo trình FPTBài 2 Cơ chế làm việc của CSS - Giáo trình FPT
Bài 2 Cơ chế làm việc của CSS - Giáo trình FPT
 
BÀI 5 Làm việc với CSS3 - Giáo trình FPT
BÀI 5 Làm việc với CSS3 - Giáo trình FPTBÀI 5 Làm việc với CSS3 - Giáo trình FPT
BÀI 5 Làm việc với CSS3 - Giáo trình FPT
 
Bài 2 Cài Đặt Joomla
Bài 2 Cài Đặt JoomlaBài 2 Cài Đặt Joomla
Bài 2 Cài Đặt Joomla
 
Bài 6 Thiết kế các thành phần giao diện - Giáo trình FPT
Bài 6 Thiết kế các thành phần giao diện - Giáo trình FPTBài 6 Thiết kế các thành phần giao diện - Giáo trình FPT
Bài 6 Thiết kế các thành phần giao diện - Giáo trình FPT
 
BÀI 3 Làm việc với JAVASCRIPT và JQUERY - Giáo trình FPT
BÀI 3 Làm việc với JAVASCRIPT và JQUERY - Giáo trình FPTBÀI 3 Làm việc với JAVASCRIPT và JQUERY - Giáo trình FPT
BÀI 3 Làm việc với JAVASCRIPT và JQUERY - Giáo trình FPT
 
Bài 1 XHTML: Cấu trúc nội dung web - Giáo trình FPT
Bài 1 XHTML: Cấu trúc nội dung web - Giáo trình FPTBài 1 XHTML: Cấu trúc nội dung web - Giáo trình FPT
Bài 1 XHTML: Cấu trúc nội dung web - Giáo trình FPT
 
Bài 7: Thư viện jQuery và thư viện jQuery UI - Giáo trình FPT
Bài 7: Thư viện jQuery và thư viện jQuery UI - Giáo trình FPTBài 7: Thư viện jQuery và thư viện jQuery UI - Giáo trình FPT
Bài 7: Thư viện jQuery và thư viện jQuery UI - Giáo trình FPT
 
Bài 3: Làm việc với kiểu dữ liệu và mã kịch bản - Giáo trình FPT
Bài 3: Làm việc với kiểu dữ liệu và mã kịch bản - Giáo trình FPTBài 3: Làm việc với kiểu dữ liệu và mã kịch bản - Giáo trình FPT
Bài 3: Làm việc với kiểu dữ liệu và mã kịch bản - Giáo trình FPT
 

Similar to 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

Thuc thi menh lenh voi co so du lieu
Thuc thi menh lenh voi co so du lieuThuc thi menh lenh voi co so du lieu
Thuc thi menh lenh voi co so du lieu
truong le hung
 
2.gioi thieu co ban ado.net cho nguoi lap trinh c#
2.gioi thieu co ban ado.net cho nguoi lap trinh c#2.gioi thieu co ban ado.net cho nguoi lap trinh c#
2.gioi thieu co ban ado.net cho nguoi lap trinh c#
Dao Uit
 
4.thuc thi menh lenh voi co so du lieu
4.thuc thi menh lenh voi co so du lieu4.thuc thi menh lenh voi co so du lieu
4.thuc thi menh lenh voi co so du lieu
Dao Uit
 
Lap trinhcosodulieuvoi c-sharp_phan-2
Lap trinhcosodulieuvoi c-sharp_phan-2Lap trinhcosodulieuvoi c-sharp_phan-2
Lap trinhcosodulieuvoi c-sharp_phan-2
Hiển Phùng
 
3.tao mot ket noi toi co so du lieu dung c#
3.tao mot ket noi toi co so du lieu dung c#3.tao mot ket noi toi co so du lieu dung c#
3.tao mot ket noi toi co so du lieu dung c#
Dao Uit
 
Cach su dung databinding
Cach su dung databindingCach su dung databinding
Cach su dung databinding
truong le hung
 
7.databinding
7.databinding7.databinding
7.databinding
Dao Uit
 
7 databinding-120306231825-phpapp02(1)
7 databinding-120306231825-phpapp02(1)7 databinding-120306231825-phpapp02(1)
7 databinding-120306231825-phpapp02(1)
TI Anh
 
S vnet.vn 51. [silde bài giảng] lập trình trên môi trường windows với ado.net...
S vnet.vn 51. [silde bài giảng] lập trình trên môi trường windows với ado.net...S vnet.vn 51. [silde bài giảng] lập trình trên môi trường windows với ado.net...
S vnet.vn 51. [silde bài giảng] lập trình trên môi trường windows với ado.net...
zzsunzz
 

Similar to 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 (20)

Thuc thi menh lenh voi co so du lieu
Thuc thi menh lenh voi co so du lieuThuc thi menh lenh voi co so du lieu
Thuc thi menh lenh voi co so du lieu
 
2.gioi thieu co ban ado.net cho nguoi lap trinh c#
2.gioi thieu co ban ado.net cho nguoi lap trinh c#2.gioi thieu co ban ado.net cho nguoi lap trinh c#
2.gioi thieu co ban ado.net cho nguoi lap trinh c#
 
Ung dung web chuong 6
Ung dung web  chuong 6Ung dung web  chuong 6
Ung dung web chuong 6
 
4.thuc thi menh lenh voi co so du lieu
4.thuc thi menh lenh voi co so du lieu4.thuc thi menh lenh voi co so du lieu
4.thuc thi menh lenh voi co so du lieu
 
C# co ban 10
C# co ban 10C# co ban 10
C# co ban 10
 
Lap trinhcosodulieuvoi c-sharp_phan-2
Lap trinhcosodulieuvoi c-sharp_phan-2Lap trinhcosodulieuvoi c-sharp_phan-2
Lap trinhcosodulieuvoi c-sharp_phan-2
 
ado.net
ado.netado.net
ado.net
 
Cach su dung data reader
Cach su dung data readerCach su dung data reader
Cach su dung data reader
 
Aspnet 3.5 _02
Aspnet 3.5 _02Aspnet 3.5 _02
Aspnet 3.5 _02
 
01 chuong1-gioithieuado-140404114504-phpapp01
01 chuong1-gioithieuado-140404114504-phpapp0101 chuong1-gioithieuado-140404114504-phpapp01
01 chuong1-gioithieuado-140404114504-phpapp01
 
3.tao mot ket noi toi co so du lieu dung c#
3.tao mot ket noi toi co so du lieu dung c#3.tao mot ket noi toi co so du lieu dung c#
3.tao mot ket noi toi co so du lieu dung c#
 
LINQ presentation
LINQ presentationLINQ presentation
LINQ presentation
 
Cach su dung databinding
Cach su dung databindingCach su dung databinding
Cach su dung databinding
 
7.databinding
7.databinding7.databinding
7.databinding
 
LinQ
LinQLinQ
LinQ
 
7 databinding-120306231825-phpapp02(1)
7 databinding-120306231825-phpapp02(1)7 databinding-120306231825-phpapp02(1)
7 databinding-120306231825-phpapp02(1)
 
Ch06
Ch06Ch06
Ch06
 
Lập trình web với các công nghệ phổ biến
Lập trình web với các công nghệ phổ biếnLập trình web với các công nghệ phổ biến
Lập trình web với các công nghệ phổ biến
 
S vnet.vn 51. [silde bài giảng] lập trình trên môi trường windows với ado.net...
S vnet.vn 51. [silde bài giảng] lập trình trên môi trường windows với ado.net...S vnet.vn 51. [silde bài giảng] lập trình trên môi trường windows với ado.net...
S vnet.vn 51. [silde bài giảng] lập trình trên môi trường windows với ado.net...
 
Aspnet 3.5 _05
Aspnet 3.5 _05Aspnet 3.5 _05
Aspnet 3.5 _05
 

More from MasterCode.vn

Pd fbuoi7 8--tongquanseo-mastercode.vn
Pd fbuoi7 8--tongquanseo-mastercode.vnPd fbuoi7 8--tongquanseo-mastercode.vn
Pd fbuoi7 8--tongquanseo-mastercode.vn
MasterCode.vn
 
Pd fbuoi5 6-ảnh hưởng của social media tới kết quả seo-mastercode.vn
Pd fbuoi5 6-ảnh hưởng của social media tới kết quả seo-mastercode.vnPd fbuoi5 6-ảnh hưởng của social media tới kết quả seo-mastercode.vn
Pd fbuoi5 6-ảnh hưởng của social media tới kết quả seo-mastercode.vn
MasterCode.vn
 
Pdf buoi3 4-link-building-tran-ngoc-chinh-mastercode.vn
Pdf buoi3 4-link-building-tran-ngoc-chinh-mastercode.vnPdf buoi3 4-link-building-tran-ngoc-chinh-mastercode.vn
Pdf buoi3 4-link-building-tran-ngoc-chinh-mastercode.vn
MasterCode.vn
 
Pd fbuoi3 4-kỹ thuật xây dựng back link-mastercode.vn
Pd fbuoi3 4-kỹ thuật xây dựng back link-mastercode.vnPd fbuoi3 4-kỹ thuật xây dựng back link-mastercode.vn
Pd fbuoi3 4-kỹ thuật xây dựng back link-mastercode.vn
MasterCode.vn
 

More from MasterCode.vn (20)

Pd ftai lieu-tieng-anh-cho-nguoi-moi-bat-dau-mastercode.vn
Pd ftai lieu-tieng-anh-cho-nguoi-moi-bat-dau-mastercode.vnPd ftai lieu-tieng-anh-cho-nguoi-moi-bat-dau-mastercode.vn
Pd ftai lieu-tieng-anh-cho-nguoi-moi-bat-dau-mastercode.vn
 
Why apps-succeed-wpr-mastercode.vn
Why apps-succeed-wpr-mastercode.vnWhy apps-succeed-wpr-mastercode.vn
Why apps-succeed-wpr-mastercode.vn
 
Dzone performancemonitoring2016-mastercode.vn
Dzone performancemonitoring2016-mastercode.vnDzone performancemonitoring2016-mastercode.vn
Dzone performancemonitoring2016-mastercode.vn
 
Google công bố thông tin lịch xu hướng ngành 2017 mastercode.vn
Google công bố thông tin lịch xu hướng ngành 2017 mastercode.vnGoogle công bố thông tin lịch xu hướng ngành 2017 mastercode.vn
Google công bố thông tin lịch xu hướng ngành 2017 mastercode.vn
 
Nghiên cứu về khách hàng mastercode.vn
Nghiên cứu về khách hàng mastercode.vnNghiên cứu về khách hàng mastercode.vn
Nghiên cứu về khách hàng mastercode.vn
 
Lập trình sáng tạo creative computing textbook mastercode.vn
Lập trình sáng tạo creative computing textbook mastercode.vnLập trình sáng tạo creative computing textbook mastercode.vn
Lập trình sáng tạo creative computing textbook mastercode.vn
 
Pd fbuoi7 8--tongquanseo-mastercode.vn
Pd fbuoi7 8--tongquanseo-mastercode.vnPd fbuoi7 8--tongquanseo-mastercode.vn
Pd fbuoi7 8--tongquanseo-mastercode.vn
 
Pd fbuoi5 6-ảnh hưởng của social media tới kết quả seo-mastercode.vn
Pd fbuoi5 6-ảnh hưởng của social media tới kết quả seo-mastercode.vnPd fbuoi5 6-ảnh hưởng của social media tới kết quả seo-mastercode.vn
Pd fbuoi5 6-ảnh hưởng của social media tới kết quả seo-mastercode.vn
 
Pdf buoi3 4-link-building-tran-ngoc-chinh-mastercode.vn
Pdf buoi3 4-link-building-tran-ngoc-chinh-mastercode.vnPdf buoi3 4-link-building-tran-ngoc-chinh-mastercode.vn
Pdf buoi3 4-link-building-tran-ngoc-chinh-mastercode.vn
 
Pd fbuoi3 4-kỹ thuật xây dựng back link-mastercode.vn
Pd fbuoi3 4-kỹ thuật xây dựng back link-mastercode.vnPd fbuoi3 4-kỹ thuật xây dựng back link-mastercode.vn
Pd fbuoi3 4-kỹ thuật xây dựng back link-mastercode.vn
 
Pd fbuoi2 onpage – tối ưu hóa trang web-mastercode.vn
Pd fbuoi2 onpage – tối ưu hóa trang web-mastercode.vnPd fbuoi2 onpage – tối ưu hóa trang web-mastercode.vn
Pd fbuoi2 onpage – tối ưu hóa trang web-mastercode.vn
 
Pd fbuoi1 giới thiệu seo tools cơ bản-seo manager + seo guy-mastercode.vn
Pd fbuoi1 giới thiệu seo tools cơ bản-seo manager + seo guy-mastercode.vnPd fbuoi1 giới thiệu seo tools cơ bản-seo manager + seo guy-mastercode.vn
Pd fbuoi1 giới thiệu seo tools cơ bản-seo manager + seo guy-mastercode.vn
 
Pdf buoi1 2-on-page-tran-ngoc-chinh-mastercode.vn
Pdf buoi1 2-on-page-tran-ngoc-chinh-mastercode.vnPdf buoi1 2-on-page-tran-ngoc-chinh-mastercode.vn
Pdf buoi1 2-on-page-tran-ngoc-chinh-mastercode.vn
 
Pdfbài 7 máy tính xác tay và máy in bảo trì sự cố máy tính-mastercode.vn
Pdfbài 7 máy tính xác tay và máy in   bảo trì sự cố máy tính-mastercode.vnPdfbài 7 máy tính xác tay và máy in   bảo trì sự cố máy tính-mastercode.vn
Pdfbài 7 máy tính xác tay và máy in bảo trì sự cố máy tính-mastercode.vn
 
Pdfbài 6 bảo trì máy tính bảo trì sự cố máy tính-mastercode.vn
Pdfbài 6 bảo trì máy tính   bảo trì sự cố máy tính-mastercode.vnPdfbài 6 bảo trì máy tính   bảo trì sự cố máy tính-mastercode.vn
Pdfbài 6 bảo trì máy tính bảo trì sự cố máy tính-mastercode.vn
 
Pdfbài 5 bảo trì và tối ưu windows bảo trì sự cố máy tính-mastercode.vn
Pdfbài 5 bảo trì và tối ưu windows   bảo trì sự cố máy tính-mastercode.vnPdfbài 5 bảo trì và tối ưu windows   bảo trì sự cố máy tính-mastercode.vn
Pdfbài 5 bảo trì và tối ưu windows bảo trì sự cố máy tính-mastercode.vn
 
Pdfbài 4 ổ cứng hard drive bảo trì sự cố máy tính-mastercode.vn
Pdfbài 4 ổ cứng hard drive   bảo trì sự cố máy tính-mastercode.vnPdfbài 4 ổ cứng hard drive   bảo trì sự cố máy tính-mastercode.vn
Pdfbài 4 ổ cứng hard drive bảo trì sự cố máy tính-mastercode.vn
 
Pdfbài 3 cpu và ram bảo trì sự cố máy tính-mastercode.vn
Pdfbài 3 cpu và ram   bảo trì sự cố máy tính-mastercode.vnPdfbài 3 cpu và ram   bảo trì sự cố máy tính-mastercode.vn
Pdfbài 3 cpu và ram bảo trì sự cố máy tính-mastercode.vn
 
Pdfbài 1 giới thiệu chung về phần cứng bảo trì sự cố máy tính-mastercode.vn
Pdfbài 1 giới thiệu chung về phần cứng   bảo trì sự cố máy tính-mastercode.vnPdfbài 1 giới thiệu chung về phần cứng   bảo trì sự cố máy tính-mastercode.vn
Pdfbài 1 giới thiệu chung về phần cứng bảo trì sự cố máy tính-mastercode.vn
 
Pdfbài 2 bo mạch chủ (main) bảo trì sự cố máy tính-mastercode.vn
Pdfbài 2 bo mạch chủ (main)   bảo trì sự cố máy tính-mastercode.vnPdfbài 2 bo mạch chủ (main)   bảo trì sự cố máy tính-mastercode.vn
Pdfbài 2 bo mạch chủ (main) bảo trì sự cố máy tính-mastercode.vn
 

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

  • 1. Bài 6: LẬP TRÌNH VỚI CSDL KIẾN TRÚC KẾT NỐI & BUỘC DỮ LIỆU
  • 2. Giới thiệu về ADO.NET Các thành phần của ADO.NET DataProvider DataSet Các loại DataProvider Sql Data Provider SqlConnection SqlDataAdapter Hệ thống bài cũ Giới thiệu về ADO.NET Các thành phần của ADO.NET DataProvider DataSet Các loại DataProvider Sql Data Provider SqlConnection SqlDataAdapter Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 2
  • 3. Mục tiêu bài học 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 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 Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 3
  • 4. THAO TÁC VỚI DỮ 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 4 THAO TÁC VỚI DỮ LIỆU BẰNG KIẾN TRÚC KẾT NỐI
  • 5. 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ới CSDL Nhược điểm: Ứng dụng vẫn kết nối với CSDL ngay cả khi không thực hiện thao tác nào với CSDL  lãng phí tài nguyê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ới CSDL Nhược điểm: Ứng dụng vẫn kết nối với CSDL ngay cả khi không thực hiện thao tác nào với CSDL  lãng phí tài nguyê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
  • 6. Truy vấn CSDL Command 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 CSDL Command 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
  • 7. Thay đổi CSDL Command kết nối với CSDL thông qua đối tượng Connection 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
  • 8. Thực thi các câu lệnh sql trên CSDL được kết nối đến Hỗ trợ kiến trúc kết nối Phươ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 đến Hỗ trợ kiến trúc kết nối Phươ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ủa CommandText được biên dịch như thế nào Parameters Chứa một collection các tham số cho lệnh
  • 9. Thực thi các câu lệnh sql trên CSDL được kết nối đến Hỗ trợ kiến trúc kết nối Phươ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 đến Hỗ trợ kiến trúc kết nối Phươ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ủa CommandText được biên dịch như thế nào Parameters Chứa một collection các tham số cho lệnh
  • 10. 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
  • 11. Thao tác thêm một bản ghi vào bảng 1 Khai báo các biến SqlConnection conn; SqlCommand cmd; 2. Khởi tạo chuỗi kết nối conn = 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 String sql = "insert into products values ('B0126','Lap trinh windows',100000,16)"; 4. khởi tạo đối tượng Sqlcommand SqlCommand cmd = new SqlCommand(sql, conn); 5. Thực thi câu lệnh truy vấn cmd.ExecuteNonQuery(); 6. Có thể đóng kết nối conn.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ến SqlConnection conn; SqlCommand cmd; 2. Khởi tạo chuỗi kết nối conn = 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 String sql = "insert into products values ('B0126','Lap trinh windows',100000,16)"; 4. khởi tạo đối tượng Sqlcommand SqlCommand cmd = new SqlCommand(sql, conn); 5. Thực thi câu lệnh truy vấn cmd.ExecuteNonQuery(); 6. Có thể đóng kết nối conn.close(); 11
  • 12. 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
  • 13. Thao tác sửa bản ghi 1 Khai báo các biến SqlConnection conn; SqlCommand cmd; 2. Khởi tạo chuỗi kết nối conn = 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 String sql = "Update products set Description='Sach PHP-Nang cao', UnitPrice=56000, OnHandQuantity=20 where ProductCode= 'S126' "; 4. khởi tạo đối tượng Sqlcommand SqlCommand cmd = new SqlCommand(sql, conn); 5. Thực thi câu lệnh truy vấn cmd.ExecuteNonQuery(); 6. Có thể đóng kết nối conn.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ến SqlConnection conn; SqlCommand cmd; 2. Khởi tạo chuỗi kết nối conn = 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 String sql = "Update products set Description='Sach PHP-Nang cao', UnitPrice=56000, OnHandQuantity=20 where ProductCode= 'S126' "; 4. khởi tạo đối tượng Sqlcommand SqlCommand cmd = new SqlCommand(sql, conn); 5. Thực thi câu lệnh truy vấn cmd.ExecuteNonQuery(); 6. Có thể đóng kết nối conn.close(); 13
  • 14. 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;User ID=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) + " where ProductCode='"+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;User ID=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) + " where ProductCode='"+txtCode.Text+"'" ; SqlCommand cmd = new SqlCommand(sql, conn); cmd.ExecuteNonQuery(); //conn.Close(); } 14
  • 15. Thao tác Xóa bản ghi 1 Khai báo các biến SqlConnection conn; SqlCommand cmd; 2. Khởi tạo chuỗi kết nối conn = 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 Sqlcommand SqlCommand cmd = new SqlCommand(sql, conn); 5. Thực thi câu lệnh truy vấn cmd.ExecuteNonQuery(); 6. Có thể đóng kết nối conn.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ến SqlConnection conn; SqlCommand cmd; 2. Khởi tạo chuỗi kết nối conn = 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 Sqlcommand SqlCommand cmd = new SqlCommand(sql, conn); 5. Thực thi câu lệnh truy vấn cmd.ExecuteNonQuery(); 6. Có thể đóng kết nối conn.close(); 15
  • 16. 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ông truy 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ông truy 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();
  • 17. SqlParameter chứa tham số cho SqlCommand Phươ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ố
  • 18. 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);
  • 19. DataReader đọc tuần tự từng dòng từ luồng dữ liệu của CSDL Tăng hiệu suất bởi đọc tuần tự từng dòng nhưng tốn tài nguyên vì hỗ trợ kiến trúc kết nối Tạ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ệu của CSDL Tăng hiệu suất bởi đọc tuần tự từng dòng nhưng tốn tài nguyên vì hỗ trợ kiến trúc kết nối Tạ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ị Boolean cho biết đã kết thúc data reader hay chưa
  • 20. 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
  • 21. Đư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
  • 22. 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 cho các TextBox
  • 23. BINDINGSOURCE Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 23 BINDINGSOURCE
  • 24. Đối tượng BindingSource là cầu nối giữa CSDL và các điều khiển trên form BindingSource chứa nguồn dữ liệu liên kết với điều khiển Cung cấp nhiều phương thức vào thuộc tính để điều hướ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 form BindingSource chứa nguồn dữ liệu liên kết với điều khiển Cung cấp nhiều phương thức vào thuộc tính để điều hướ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ển trên form BindingSource
  • 25. 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
  • 26. 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;
  • 27. Xử lý sự kiện cho button >> (chuyển đến bản ghi cuối cù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
  • 28. Demo sử dụng BindingSource để 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
  • 29. 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
  • 30. 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ối vào file config và cung cấp các lớp để đọc chuỗi kết nối từ file config  Chuỗi kết nối chỉ được lưu một nơi duy nhất trên file config 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ối vào file config và cung cấp các lớp để đọc chuỗi kết nối từ file config  Chuỗi kết nối chỉ được lưu một nơi duy nhất trên file config Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 30
  • 31. B1. Tạo file config Chọn project  Add  New Item Chọn mục Application Configuration File Demo lưu và lấy chuỗ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
  • 32. B2. Thêm chuỗi kết nối vào file config Demo lưu và lấy chuỗ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>
  • 33. B3. Lấy chuỗi kết nối Lưu ý: để sửa dụng được lớp ConfigurationManager phải add thêm assembly này vào Vào Project  Add Reference…  chọn System.Configuration Demo lưu và lấy chuỗ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);
  • 34. 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
  • 35. 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
  • 36. Sử dụng phương thức ExecuteReader của SqlCommand để lấy dữ liệu Sử dụng SqlDataReader để đọc dữ liệu vào form Sử dụng phương thức ExecuteNoneQuery của SqlCommand để thêm, sửa, xóa dữ liệu Demo thao tác với dữ 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
  • 37. 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
  • 38. Demo xử lý sự kiện Button GetCustomer private void btnGetCustomer_Click(object sender, EventArgs e) { int customerID = Convert.ToInt32(txtCustomerID.Text); //Tạo kết nối SqlConnection connection = new SqlConnection ("chuỗi-kết-nối"); //Tạo command 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); //Đọc dữ liệu và gán cho các trường connection.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ối SqlConnection connection = new SqlConnection ("chuỗi-kết-nối"); //Tạo command 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); //Đọc dữ liệu và gán cho các trường connection.Open(); SqlDataReader custReader = selectCommand.ExecuteReader(); if (custReader.Read()) { txtName.Text = custReader["Name"].ToString(); … } connection.Close(); }
  • 39. Demo xử lý sự kiện trên Accept 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();
  • 40. Ứng dụng được tổ chức theo mô hình 3 tầng như sau: Tầng hiển thị: Form Tầng xử lý nghiệp vụ: Customer, State Tầ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
  • 41. frmCustomer gọi đến lớp CustomerDB để thao tác với CSDL Dữ liệu được truyền giữa CustomerDB và frmCustomer thông qua lớp Customer Demo viết xử lý sự kiện GetCustomer 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
  • 42. 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; } }
  • 43. 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; } }
  • 44. Demo viết phương thức GetCustomer 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; }
  • 45. Xử lý sự kiện cho Button 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(); } }
  • 46. Các đối tượng SqlConnection, SqlCommand, SqlDataReader thao tác với CSDL SQL server bằng kiến trúc kết nối. Trong đó SqlConnection kết nối với CSDL; 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ên CSDL Thuộc tính DataSource của điều khiển buộc chỉ ra nguồn dữ liệu cho điều khiển (thường là bảng trên dataset) 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ằng kiến trúc kết nối. Trong đó SqlConnection kết nối với CSDL; 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ên CSDL Thuộc tính DataSource của điều khiển buộc chỉ ra nguồn dữ liệu cho điều khiển (thường là bảng trên dataset) Lập trình với CSDL - Kiến trúc kết nối & buộc dữ liệu 46
  • 47. BindingSource là cầu nối giữa CSDL và các điều khiển trên form BindingSource chứa nguồn dữ liệu liên kết với điều khiển BindingSource cung cấp nhiều phương thức vào thuộc tí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ụng kế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ển trên form BindingSource chứa nguồn dữ liệu liên kết với điều khiển BindingSource cung cấp nhiều phương thức vào thuộc tí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ụng kế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