4. 4
Khái niệm ứng dụng CSDL
Định nghĩa “Ứng dụng CSDL”: Ứng dụng CSDL
Data–Centric Applications hay
Database–Centric Applications hay
Data–Driven Application
là loại ứng dụng mà dữ liệu hay CSDL đóng vai
trò tiên quyết.
Ví dụ:
• Chương trình quản lý nhà sách
• Hệ thống chương trình quản lý ngân hàng
6. 6
Khái niệm ứng dụng CSDL
Định nghĩa “Data source” (Data storage): Nơi lưu
trữ dữ liệu. Thông thường là Database
Một số loại Data source được hổ trợ trong .NET
• MS SQL Server, Oracle, DB2, MS Access, …
9. 9
Kiến trúc ADO.NET
ADO.NET là gì?
Data sourceApplication
(C#, VB.NET, …)
Thư viện
truy cập dữ liệu
ADO.NET
• ADO.NET là một thư viện chứa các lớp thực hiện
các chức năng
– Kết nối ứng dụng với data source
– Thêm, xóa, sửa, tìm kiếm dữ liệu trong data source
Data–Driven Application
11. 11
Kiến trúc ADO.NET
Những đối tượng quan trọng trong ADO.NET
Kiến trúc ADO.NET được chia làm 2 phần
• Connected
• Disconnected
Những lớp khác nhau của ADO.NET có thể
phân loại thành: Connected và Disconnected.
Ngoại lệ là lớp DataAdapter
12. 12
Kiến trúc ADO.NET
Những đối tượng quan trọng trong ADO.NET
Application
DatabaseDataAdapter
Đối tượng Disconnected Đối tượng Connected
DataSet
DataTable
DataRow
…
Connection
Command
Parameter
…
ADO.NET
13. 13
Kiến trúc ADO.NET
Những đối tượng quan trọng trong ADO.NET
Các đối tượng Connected
• Connection
• Command
• Parameter
• DataAdapter
• DataReader
• Transaction
14. 14
Kiến trúc ADO.NET
Những đối tượng quan trọng trong ADO.NET
Các đối tượng Disconnected
• DataSet
• DataTable
• DataRow
• DataColumn
• DataView
• Constraint
• DataRelation
15. 15
Kiến trúc ADO.NET
.NET Data Providers
ADO.NET hiện thực (bao gồm) tập các lớp
connected cho từng loại CSDL
• Ví dụ: Để kết nối với MS SQL Server, chúng ta có lớp
giành riêng là SqlConnection, SqlCommand,
SqlParameter, …
Tập các lớp connected cho một CSDL nào đó được
nằm trong 1 namespace riêng
• Ví dụ:
– System.Data.SqlClient
– System.Data.OleDb
Định nghĩa “.Net Data Provider”: Là một tập lớp
connected nằm trong cùng 1 namespace và được
thiết kế để làm việc với một loại CSDL cụ thể
16. 16
Kiến trúc ADO.NET
.NET Data Providers
Application
Data
SourceDataAdapter
Đối tượng Disconnected
Đối tượng Connected
DataSet
DataTable
DataRow
…
Connection
Command
Parameter
…
.Net Data
Provider
17. 17
Kiến trúc ADO.NET
.NET Data Providers
Chọn lựa .NET Data Provider
• SQL Server .NET Data
Provider
– SQL Server version 7.0 trở
lên
• Oracle .NET Data Provider
– Oracle 8.1.6 trở lên
• OLE DB .NET Data Provider
– SQL Server 6.5, Microsoft
Access, Oracle version <
8.1.6, những data sources có
OLE DB providers
• ODBC .NET Data Provider
– Dùng cho các data sources
chỉ hổ trợ ODBC drivers
Các loại .Net Data Provider
Tên Data Source Provider Namespace
MS SQL Server 7.0 trở lên System.Data.SqlClient
Oracle 8.1.6 trở lên System.Data.OracleClient
ODBC System.Data.ODBC
OleDb System.Data.OleDb
XML trong SQL Server System.Data.SqlXml
18. 18
Kiến trúc ADO.NET
Các namespace quan trọng trong ADO.NET
• System.Data
• System.Data.Common
• System.Data.SqlClient
• System.Data.SqlTypes
• System.Data.OleDb
22. 22
Kết nối đến CSDL
Phương pháp kéo thả
Bước 1: Thiết lập Data Source
• Dùng Data Source là SQL Server 2008
• Tên CSDL: StarterDB
• Tên Table: TableName
Create Table TableName
(
IDName int primary key,
ValueName varchar(100)
)
Go
Insert into TableName values(‘1’, ‘Hello’)
Go
23. 23
Kết nối đến CSDL
Phương pháp kéo thả
Bước 2: Tạo ứng dụng Windows Forms
• Tên ứng dụng: VDKeoTha
• Mở form Form1 trong Design mode
Bước 3: Mở cửa sổ Data Source
• Chọn Data Show Data Sources
• Trong cửa số Data Source: Click vào liên kết
Add New Data Source
24. 24
Kết nối đến CSDL
Phương pháp kéo thả
Bước 4: Chọn loại Data Source
• Chọn Database
• Click nút Next
25. 25
Kết nối đến CSDL
Phương pháp kéo thả
Bước 5: Thiết lập thông tin kết nối
• Click vào nút New Connection
• Chọn Microsoft SQL Server
• Click nút “Continue”
26. 26
Kết nối đến CSDL
Phương pháp kéo thả
• Điền các thông tin về
CSDL
• Click Test Connection
để kiểm tra thông tin
nhập vào
• Click OK 2 lần để chấp
nhận Data Source
27. 27
Kết nối đến CSDL
Phương pháp kéo thả
• Thông tin kết nối được lưu trong 1 chuỗi kết
nối (Connection string)
28. 28
Kết nối đến CSDL
Phương pháp kéo thả
Bước 6: Chọn lưu chuỗi kết nối
29. 29
Kết nối đến CSDL
Phương pháp kéo thả
Bước 7: Chọn các đối tượng trong CSDL
• Chọn các bảng, các cột
• Click nút Finish
30. 30
Kết nối đến CSDL
Phương pháp kéo thả
Bước 8: Chọn các hiển thị dữ liệu trên Form
• Lúc này một data source có tên
StarterDataSet được thêm vào ứng dụng
• Click nút Drop-Down kế bảng TableName
Chọn DataGridView
31. 31
Kết nối đến CSDL
Phương pháp kéo thả
Bước 9: Kéo và Thả
• Kéo bảng TableName vào trong Form1
• Thao tác trên sinh ra một số controls
32. 32
Kết nối đến CSDL
Phương pháp kéo thả
Một số code do IDE sinh ra
• Chuỗi kết nối trong file app.config
33. 33
Kết nối đến CSDL
Phương pháp kéo thả
• Code trong form
35. 35
Kết nối đến CSDL
Bước 1: using một số namespace
Bước 2: Tạo kết nối: Tạo chuỗi kết nối + Đối
tượng kết nối
Bước 3: Tạo đối tượng command chứa câu
SQL
Bước 4: Mở kết nối
Bước 5: Chạy command
Bước 6: Đóng kết nối
Bước 7: Hiện dữ liệu
36. 36
Kết nối đến CSDL
Namespace
Với OLE DB
• using System.Data;
• using System.Data.OleDb;
Với SQL Server
• using System.Data;
• using System.Data.SqlClient;
38. 38
Kết nối đến CSDL
Chuỗi kết nối
Để mở kết nối, chúng ta cần chỉ ra một số thông
tin (tham số): tên server, tên csdl, user ID,
password, …
Mỗi data source cần một tập các thông tin khác
nhau
Định nghĩa “Chuỗi kết nối” (Connection String):
Là 1 tập các thông tin cung cấp cho một thiết
lập kết nối (tham số), và có hình thức các cặp
key-value cách nhau bằng dấu “;”
parameterName1=value1; parameterName2=value2;…
39. 39
Chuỗi kết nối
Chuỗi kết nối cho OleDB và MS SQL Server
Chuỗi kết nối cho CSDL OleDB (MS Access)
"Provider=Microsoft.Jet.OleDb.4.0;
Data Source=DuLieu.mdb"
Chuỗi kết nối cho CSDL MS SQL Server
"Server hay Data source=tenServer;
Database hay Initial Catalog=tenCSDL;
User Id=tenUser;
Password=tenPass"
"Server=local;
Database=pubs;
Integrated Security=SSPI"
40. 40
Kết nối đến CSDL
Chuỗi kết nối
Bảo mật CSDL SQL Server
• Windows Authentication
• Mixed Mode
– Windows Authentication
– SQL Server Authentication
41. 41
Kết nối đến CSDL
Chuỗi kết nối
Một số từ khóa liên quan đến chuỗi kết nối cho SQL Server
Keyword Ý nghĩa
Data Source, Server, addr,
address, network address
Tên hay địa chỉ của database server.
Initial Catalog, Database Tên của database
Integrated Security,
trusted_connection
Bảo mật dựa trên HĐH Windows. Có thể gán bằng true,
false, hay sspi. Default là false.
User ID, uid, user user name để kết nối đến SQL Server khi không dùng
trusted connection.
Password, pwd password để kết nối đến SQL Server khi không dùng trusted
connection.
Pooling Khi bằng true, dùng pool để lưu trữ các connection. Default
là true
Max Pool Size Số connection tối đa được lưu trong connection pool.
Default là 100.
Min Pool Size Số connection tối thiểu được lưu trong connection pool.
Default là 0.
Connect Timeout, connection
timeout, timeout
Thời gian chờ (tính bằng giây) khi kết nối đến data store.
Default là 15 giây.
42. 42
Kết nối đến CSDL
Đối tượng Connection
Tạo đối tượng kết nối
Kết hợp đối tượng kết nối với chuỗi kết nối
Dùng Constructor của lớp Connection
43. 43
Kết nối đến CSDL
Đối tượng Connection
Tạo một đối tượng của lớp Connection
(tương ứng với data source cho trước)
SqlConnection conn = new SqlConnection();
Chỉ ra các tham số kết nối dùng property
ConnectionString
string strConn =
"Data Source=(local);
Initial Catalog=demoDB;
Integrated Security=SSPI";
conn.ConnectionString=strConn;
44. 44
Kết nối đến CSDL
Đối tượng Connection
Có thể dùng constructor của lớp Connection
string strConn =
"Data Source=(local);
Initial Catalog=demoDB;
Integrated Security=SSPI";
SqlConnection conn = new SqlConnection(strConn);
45. 45
Kết nối đến CSDL
Đối tượng Connection
Mở kết nối
Đóng kết nối
Kiểm tra trạng thái đối tượng Connection
46. 46
Kết nối đến CSDL
Đối tượng Connection
Phương thức Open()
Một số bước được thực hiện khi mở kết nối MỚI
• Thiết lập kênh vật lý (socket hay pipe)
• Bắt tay với Server
• Phân tích chuỗi kết nối
• Xác thực với Server
• …
tốn
thời gian
47. 47
Kết nối đến CSDL
Đối tượng Connection
Phương thức Close()
• Đặt connection đã mở vào connection pooler
Phương thức Dispose()
• Đặt connection vào connection pooler
• Giải phóng các tài nguyên (Cho phép GC dọn dẹp)
48. 48
Kết nối đến CSDL
Đối tượng Connection
Property State
• ConnectionState.Open
• ConnectionState.Closed
SqlConnection conn = new SqlConnection(strConn);
…
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
49. 49
Kết nối đến CSDL
Đối tượng Connection
string strConn =
"Data Source=(local);
Initial Catalog=demoDB;
Integrated Security=SSPI";
SqlConnection conn = new SqlConnection(strConn);
try
{
conn.Open();
//…
}
catch (SqlException ex)
{
//…
}
finally
{
conn.Dispose();
}
51. 51
Lưu trữ chuỗi kết nối
Đọc chuỗi kết nối từ file app.config
• References: System.configuration
• Namespace: using System.Configuration;
• Sử dụng lớp: ConfigurationManager
string strConn;
strConn = ConfigurationManager.ConnectionStrings["ten"].ConnectionString;
52. 52
Tóm tắt chương 1
ADO.NET là thư viện giúp việc kết nối giữa ứng dụng
và data source. Thư viện này nằm trong System.Data
ADO.NET gồm 2 phần
• Disconnected
• Connected
Phần Disconnected sử dụng phần Connected để kết
nối với data source
Một số tiếp cận viết code ADO.NET
• Phương pháp Drap-and-drop
• Phương pháp Tự viết code
Editor's Notes
Ung dung CSDL = CSDL + Xuly
Database = data source
ADO.NET là một tập các lớp nằm trong bộ thư viện lớp cơ sở của .NET Framework, cho phép các ứng dụng Windows (như C#, VB.NET…) hay ứng dụng web (như ASP.NET) thao tác dễ dàng với các nguồn dữ liệu
Hinh trên tổng quát hơn
Data source:
lưu trữ dữ liệu dựa trên file
lưu trữ dữ liệu dựa trên server
Data–Driven Application
Ứng dụng hướng dữ liệu
ADO.NET gom 2 phan: Phan tuong tac voi data source va phan luu tru du lieu
Phần connected là tập đối tượng yêu cầu phải có một kết nối đang mở khi chúng làm việc và tương tác với data source
DataAdapter là lớp giao tiếp giữa Connected và Disconnected
Application dùng Đối tượng Connected hay Disconnected
Disconnected dùng Connected, ngược lại không được
ADO.NET hien thuc cac đối tượng connected theo từng loại csdl cụ thể
Chú ý:
Sql server 7.0 &lt;-&gt;2000
Use System.Data.SqlClient for SQL Server 7.0 and Later
The commonly used classes in System.Data.SqlClient are SqlConnection, SqlCommand, SqlDataAdapter, and SqlDataReader.
Use System.Data.OracleClient for Oracle
- The commonly used classes in System.Data.OracleClient are OracleConnection, OracleCommand, OracleDataAdapter, and OracleDataReader.
Use System.Data.ODBC for ODBC Data Sources
- The commonly used classes in System.Data.Odbc are OdbcConnection, OdbcCommand, OdbcDataAdapter, and OdbcDataReader.
Use System.Data.OleDb for SQL Server 6.5 or OLE DB Providers
- The commonly used classes in System.Data.OleDb are OleDbConnection, OleDbCommand, OleDbDataAdapter, and OleDbDataReader.
Data: Định nghĩa các kiểu để biểu diễn dữ liệu
Common: Các kiểu để chia sẻ giữa các provider
SqlClient: Các kiểu để kết nối đến SQL Server
OleDB: Các kiểu để kết nối đến OLE DB
SqlType: Các kiểu dữ liệu trong SQL Server
Một cách uyển chuyển để cung cấp thông tin cho một thiết lập kết nối là dùng một chuỗi kế nối
Nếu không chỉ đường dẫn tuyệt đối thi ADO.NET tìm csdl trong đường dẫn của ứng dụng
SSPI stands for the Security Support Provider Interface
KeywordDescription
Data Source, addr, address, network address, serverThe name or IP address of the database server.
Failover PartnerProvides support for database mirroring in SQL Server 2005.
AttachDbFilename, extended properties, initial filenameThe full or relative path and name of a file containing the database to be attached to. The path supports the keyword string |DataDirectory|, which points to the application&apos;s data directory. The database must reside on a local drive. The log filename must be in the format &lt;database-File-Name&gt;_log.ldf or it will not be found. If the log file is not found, a new log file is created.
Initial Catalog, databaseThe name of the database to use.
Integrated Security, trusted_connectionUsed to connect to SQL Server using a secure connection, where authentication is through the user&apos;s domain account. Can be set to true, false, or sspi. The default is false.
Persist Security Info, persistsecurityinfoIf set to true, retrieving the connection string returns the complete connection string that was originally provided. If set to false, the connection string contains the information that was originally provided, minus the security information. The default is false.
User ID, uid, userThe user name to use to connect to the SQL Server when not using a trusted connection.
Password, pwdThe password to use to log in to SQL Server when not using a trusted connection.
EnlistWhen set to true, the pooler automatically enlists the connection into the caller thread&apos;s ongoing transaction context.
PoolingWhen set to true, causes the request for a new connection to be drawn from the pool. If the pool does not exist, it is created.
Max Pool SizeSpecifies the maximum allowed connections in the connection pool. The default is 100.
Min Pool SizeSpecifies the minimum number of connections to keep in the pool. The default is 0.
Asynchronous Processing, asyncWhen set to true, enables execution of asynchronous commands on the connection. Synchronous commands should use a different connection, to minimize resource usage. The default is false.
Connection ResetIndicates that the database connection will be reset when the connection is removed from the pool. The default is true. A setting of false results in fewer round-trips to the server when creating a connection, but the connection state is not updated.
MultipleActiveResultSetsWhen set to true, allows for the retrieval of multiple forward-only, read-only result sets on the same connection. The default is false.
ReplicationUsed by SQL Server for replication.
Connect Timeout, connection timeout, timeoutThe time in seconds to wait while an attempt is made to connect to the data store. The default is 15 seconds.
EncryptIf Encrypt is set to true and SQL Server has a certificate installed, all communication between the client and server is SSL encrypted.
Load Balance Timeout, connection lifetimeThe maximum time in seconds that a pooled connection should live. The maximum time is checked only when the connection is returned to the pool. This setting is useful in load-balanced cluster configurations to force a balance between a server that is on line and a server that has just started. The default is 0.
Network Library, net, networkThe network library DLL to use when connecting to SQL Server. Allowed libraries include dbmssocn (TCP/IP), dbnmpntw (Named Pipes), dbmsrpcn (Multiprotocol), dbmsadsn (AppleTalk), dbmsgnet (VIA), dbmsipcn (Shared Memory), and dbmsspxn (IPX/SPX).
The default is dbmssocn (TCP/IP), but if a network is not specified and either &quot;.&quot; or &quot;(local)&quot; is specified for the server, shared memory is used as the default.
Packet SizeThe size in bytes for each packet that is sent to SQL Server. The default is 8192.
Application Name, appThe name of the application. If not set, this defaults to .NET SQL Client Data Provider.
Current Language, languageThe SQL Server language record name.
Workstation ID, wsidThe name of the client computer that is connecting to SQL Server.
Chú ý:
1. Rieng MS Access 2003
Provider = “Microsoft.jet.oledb.4.0; data source=tenfile.mdb”
Data source lúc này không tương đương với server, addr, … (Nghĩa là chỉ dùng data source chỉ ra file csdl ms access)
2. Rieng MS Access 2007
Provider=“Microsoft.ace.oledb.12; data source=tenfile.accdb”
Cach 1
Tạo đối tượng kết nối để chuẩn bị mở kết nối
SSPI = Security Support Provider Interface
Cach 2
Mo cang tre cang tot
Dong cang som cang tot
Tot nhat: Dispose
Tot: Close
Te nhat: Không close và dispose
Ném ra 2 ngoại lệ
InvalidOperationException Cannot open a connection without specifying a data source or server.or The connection is already open.
SqlException A connection-level error occurred while opening the connection. If the Number property contains the value 18487 or 18488, this indicates that the specified password has expired or must be reset. See the ChangePassword method for more information.