* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download NET Data Access
Microsoft SQL Server wikipedia , lookup
Extensible Storage Engine wikipedia , lookup
Open Database Connectivity wikipedia , lookup
Relational model wikipedia , lookup
Clusterpoint wikipedia , lookup
Entity–attribute–value model wikipedia , lookup
Functional Database Model wikipedia , lookup
.NET Data Access 台南市教育局網路中心 在職教師校務行政系統程式開發 進階班 行政網路組 [email protected] Design Goals for ADO.NET • Leverage Current ADO Knowledge • Support the N-Tier Programming Model • Integrate XML Support Why ADO.NET? ADO vs. ADO.NET • • ADO.NET ADO – Disconnected access – Connected access – Logical data model – Physical data model – The DataSet based data – RecordSet based data – DataSet is multi-table – RecordSet is ‘one’ table • > 1 table or source does • > 1 table requires a not require a JOIN database JOIN • Relationships remain: • Data is “flattened”: lose navigation is relational relationships – XML schema Data types – COM/COM+ data types – No data type conversions required – Data via COM marshalling – XML is plaintext: ‘Firewall – Blocked by firewalls friendly’ (DCOM, binary) ADO.NET Architecture() System.Data DataSet System.Data.SqlClient System.Data.OleDb .NET Data Providers System.Data.SQLTypes ADO.NET Architecture(2) • XML and ADO.NET • ADO.NET Components .NET Data Provider • • • Retrieve data from a data source and reconcile changes made to it with the data source The link between data source and application Two Providers out of the box: – .NET SQL Data Provider: SqlClient – .NET OLE DB Data Provider: OleDb ADO.NET Data Provider Core Classes System.Data.<Provider> Connection Connect to data source Command Execute Command against data source Data Reader Reads a forward-only readonly stream of data from a data source Data Adapter Populates a DataSet and resolves updates with data source Connection Class • • • • Represent a unique session with a data source Create, open, close a connection to a data source Functionality and methods to perform transactions Connection example: String conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=NWIND_RW.MDB"; OleDbConnection aConn = new OleDbConnection(conStr); aConn.Open(); // Execute Queries using OleDbCommand Class aConn.Close(); Connection • OleDbConnection Provider=MSDAORA; Data Source=ORACLE8i7; User ID=OLEDB; Password=OLEDB Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\bin\LocalAccess40.mdb; Provider=SQLOLEDB;Data Source=MySQLServer;Integrated Security=SSPI; • SqlConnection user id=sa;password=aU98rrx2;initial catalog=northwind;data source=mySQLServer;Connect Timeout=30 Command Class • • Represents a query to execute on the data source Methods of interest: – ExecuteNonQuery: Executes a SQL statement that doesn’t return any rows – ExecuteReader: Returns a DataReader – ExecuteScalar: Executes the query and returns the first column of the first row String SqlStr = “INSERT INTO Customers (CustId,FName,Lname) ;” + “Values (‘Matt’,’Stephen’)”; SqlCommand myCommand = new SqlCommand(SqlStr , myConnection); myCommand.Connection.Open(); myCommand.ExecuteNonQuery(); myConnection.Close(); DataAdapter Class • • • Bridge between the DataSet and the data store Means to modify the DataSet and data source Properties of Interest: DeleteCommand, InsertCommand, SelectCommand, UpdateCommand • • TableMappings: Maps source and DataTable Inherits methods from DbDataAdapter class – – public virtual int Fill(DataSet,”Tablename”); public virtual int update(DataSet,”Tablename”); Data Store DataAdapter DataSet DataReader • • Forward-only data access “Lightweight” programming model – Less overhead than using Command • • • Instantiated by the Command class Execute method Ties up the Command until it is finished reading Methods to retrieve data: – By index and optionally column type: GetString, GetInt32, and so on – Read: Advances reader to next record DataReader Sample // Code for creating the Connection “Conn” not shown String myQuery = “SELECT * FROM Customers”; Conn.Open(); OleDbCommand myCmd = new OleDbCommand( myQuery, Conn ); // Declare the DataReader... OleDbDataReader myDataReader; // Instantiate the DataReader with ExecuteReader(...) ... myDataReader = myCmd.ExecuteReader(); // Always call Read before accessing data. while(myDataReader.Read()) { Console.WriteLine(myDataReader.GetString(0)); } // Always Close the reader and the connection when done myDataReader.Close(); Conn.Close(); System.Data Principal Classes System.Data Contains the ‘main’ classes of ADO.NET DataSet In-memory cache of database DataTable In-memory cache of database table DataRow Used to manipulate a row in a DataTable DataColumn Used to define the columns in a DataTable DataRelation Used to relate two DataTables to each other DataView Used to create a view on a DataSet System.Data: DataSet Overview DataSet Tables DataTable DataView DataRow(s) Relations DataRelation DataRelation DataColumn Constraint(s) DataTable DataTable DataView System.Data: DataSet • • • An in-memory cache of data from a data source via DataAdapter XML used to read and write data and schema Common way to represent and manipulate data – – • Logical or physical representation of data, depending on: – – • Universal data container Not just for use with databases The query/result set Whether DataTables and Relations exist Designed to be disconnected from the data source – Connect, execute query, disconnect System.Data: DataTable • • • • May be mapped to a physical table in the data source Can be related to one another through DataRelations Optimistic concurrency / locking Properties of Interest: – Columns: Returns DataColumnCollection of DataColumns – Rows: Returns DataRow objects as a DataRowCollection – Constraints: Returns the table’s ConstraintCollection System.Data: DataSet & DataTable • Create a DataTable and add it to a DataSet DataSet ds = new DataSet(); // Create DataTable object: “Customers”. DataTable dt = new DataTable( “Customers” ); // Create and add columns to the table // 1. Explicitly create and Add a DataColumn DataColumn dc = new DataColumn( “CustID”, typeof(Int16) ); dt.Columns.Add( dc ); // 2. Implicitly Create and Add columns (DataColumn). dt.Columns.Add( “First_Name”, typeof(String) ); dt.Columns.Add( “Last_Name”, typeof(String) ); // Add the DataTable object to the DataSet ds.Tables.Add( dt ); 如何存取資料庫 • ADO .NET 資料存取模型 – 資料庫連線 (Connection) • SqlConnection 與 OleDbConnection – 執行 SQL 語法 (Commands) • SqlCommand 與 OleDbCommand – – – ExecuteNonQuery (不傳回資料列) ExecuteScalar (傳回單一列資料) ExecuteReader (傳回多列資料) – 取得資料 • DataReader • DataAdapter 與 DataSet 如何使用資料庫連線 • 使用資料庫連線的步驟 – 建立資料庫連線物件 OleDbConnection conn = new OleDbConnection() ; – 設定連線字串 conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; User ID=Admin; Password=123; Data Source=C:\Northwind.mdb" ; – – – 開啟資料庫連線 conn.Open() ; : 關閉資料庫連線 conn.Close() ; Connection • • SqlConnection – 只能夠連接 Microsoft SQL Server conn.ConnectionString = – – "User ID=sa; Password=; 效能最佳化 需引用 System.Data.SqlClient Server=localhost;Database=Northwind" ; OleDbConnection –– – – – 可以透過 OLE DB 連接不同的資料庫 conn.ConnectionString = 應用範圍最廣 "Provider=SQLOLEDB; 需引用 System.Data.OleDb User ID=sa; Password=; 一樣可以連接 Microsoft SQL Server Data Source=localhost; Initial Catalog=Northwind" ; Command • SqlCommand 與 OleDbCommand • 支援多種 SQL 命令 • – DCL : GRANT, REVOKE, DENY – DDL : CREATE, ALTER, DROP – DML : SELECT, INSERT, DELETE, UPDATE – 其它 : Stored Procedure, CURSOR, … 允許加入參數 (Parameters) 執行 SQL 語法 • 執行非查詢式 SQL 語法 – 建立一個 Command 物件 SqlCommand cmd = new SqlCommand("update… where OrderID=@ID", conn) ; – 建立參數物件param = new SqlParameter SqlParameter("@ID", typeof(int)) ; – 設定參數值 = 12 ; param.Value – 將參數加入 Command 物件 ; cmd.Parameters.Add(param) – 執行 SQL 語法= cmd.ExecuteNonQuery() ; int rowEffects 如何執行 SQL 語法 • 執行查詢式 (單筆記錄) SQL 語法 – 建立一個 string sql =Command "select cid 物件 from… where OrderID=@ID" ; – SqlCommand cmd = new SqlCommand(sql, conn) ; – 建立參數物件param = new SqlParameter SqlParameter("@ID", typeof(int)) ; – 設定參數值 = 12 ; param.Value – 將參數加入 Command 物件 ; cmd.Parameters.Add(param) – 執行 Command int myCID = (int)並取得結果 cmd.ExecuteScalar() ; 如何處理多筆記錄 • 執行查詢式 (多筆記錄) SQL 語法 – 建立一個 物件 Qty from MyOrders" ; string sql =Command "select PName, – SqlCommand cmd = new SqlCommand(sql, conn) ; – 執行 Commanddr並取得 DataReader SqlDataReader = cmd.ExecuteReader() ; – 讀取下一筆記錄 while ( dr.Read() )(如果 true 表示有資料) { 取得第一個欄位 string pname = dr.GetString(0) ; 取得第二個欄位 int qty = dr.GetInt32(1) ; Console.WriteLine("{0}, {1}", pname, qty) ; } 如何執行 Stored Procedure • 執行 Stored Procedure – 建立一個 Command 物件SqlCommand() ; SqlCommand cmd = new – 設定使用連線 = conn ; cmd.Connection – 設定命令名稱 = "DeleteOrder" ; cmd.ComandText – 設定 CommandType= cmd.CommandType CommandType.StoredProcedure ; – 建立參數 cmd.Parameters.Add("@ID", orderID) ; – 執行 Stored Procedure int rowEffects = cmd.ExecuteNonQuery() ; Data Access Layer Calling stored procedures Dim sqlconn As SqlConnection = New SqlConnection(connectionstring)a Dim sqlcomm As SqlCommand = New SqlCommand() sqlcomm.CommandType = CommandType.StoredProcedure sqlcomm.CommandText = "DemoProc“ ‘Open Connection sqlconn.Open() sqlcomm.Connection = sqlconn 'Create parameters sqlcomm.Parameters.Add(New SqlParameter("@input1", SqlDbType.Int)) sqlcomm.Parameters.Add(New SqlParameter("@input2", SqlDbType.Int)) sqlcomm.Parameters.Add(New SqlParameter("@output1", SqlDbType.Int)).Direction = ParameterDirection.Output ‘Set Parameter Values sqlcomm.Parameters.Item("@input1").Value = 123 sqlcomm.Parameters.Item("@input2").Value = 456 sqlcomm.ExecuteNonQuery() ‘Access Output Response.write (sqlComm.Parameters.Item(“@output1”).Value.ToString()) WebForms 控制項資料繫結 <%@ Import Namespace="System.Data.SqlClient" %> <html><head><script language="C#" runat=server> public void Page_Load(Object sender, EventArgs args) { // 建立資料庫連線,並取得 DataReader SqlConnection cnn = new SqlConnection("server=localhost;uid=sa;"); conn.Open(); SqlCommand cmd = new SqlCommand("select * from customers", conn); SqlDataReader dr = cmd.ExecuteReader(); // 將資料來源繫結到控制項 dgCustomers.DataSource = dr; dgCustomers.DataBind(); } </script></head><body> <asp:DataGrid id="dgCustomers" runat="server"/> </body></html> 自訂 Data Provider • ADO .NET 共有那些 Data Provider – – – – SQL Data Provider OLE DB Data Provider ODBC Data Provider (外掛) Oracle Data Provider (未來) DataAdapter 與 DataSet • DataSet 與資料庫之間透過 DataAdapter 進行 存取動作 DataAdapter SelectCommand Fill 資 料 庫 InsertCommand Update UpdateCommand DeleteCommand DataSet 如何取得 DataSet • 透過 DataAdapter 取得 DataSet 資料 – 建立一個 Command SqlCommand cmd = new SqlCommand() ; 用來執行 SELECT 語法; cmd.Connection = conn cmd.ComandTextda=="select * from Customers" ; – SqlDataAdapter new SqlDataAdapter( 建立 DataAdapter – SqlDataAdapter da物件 = "select new SqlDataAdapter() ; conn) ; * from Customers", – 設定 SelectCommand da.SelectCommand = cmd; – 建立一個 物件 DataSet dsDataSet = new DataSet("Customers") ; – 使用 DataAdapter 物件的 Fill 方法 da.Fill(ds) ; 填滿 DataSet DataSet 的結構 • 透過欄位號碼或欄位名稱來存取 DataRow (每一筆記錄) 中包含了多個欄位 DataRow 的資料 DataTable 使用 Tables[表格號碼] 可以包含多筆資料列 或 Tables["表格名稱"] (Row),組成 Rows 集合 DataSet 可以包含多個表格 (Table),組成 Tables 集合 每一個 Rows Rows[列號碼] 集合中的每一筆資料記錄都是一個 DataSet 中的表格都是一個 來引用 Tables 中的任何一個表格。 DataTable DataRow 物件 物件 來引用 Tables可以取得資料總筆數) 中的任何一個表格。 (Rows.Count (Tables.Count 可以取得表格數目) DataSet Tables[0] DataTable Tables[1] Tables[2] DataRow Rows[0] Tables[3] Rows[1] : 1 Rows[2] 2 Tables 0 3 : 性別 Rows 姓名 電話 血型 : : 男 王小明 AB : (04)2222-2222 : : DataRow: row = ds.Tables[0].Rows[3]; : string name = row[0]; string phone = row["電話"]; 如何瀏覽 DataSet 中的資料 for 迴圈瀏覽 DataSet 資料資料 • 使用 foreach 迴圈瀏覽 DataSet for(int c=0;c < ds.Tables[0].Columns.Count; foreach(DataRow cust in ds.Tables[0].Rows) c++) { { DataColumn dc = ds.Tables[0].Columns[c] ; Console.Write("{0}\t", dc.ColumnName) ; Console.WriteLine("\n客戶: {0}", cust["Name"]); } foreach(DataRow ord in cust.GetChildRows("odr")) for(int { r = 0;r < ds.Tables[0].Rows.Count;r++) { string cName = ds.Tables[0].Rows[r]["客戶名稱"] Console.Write("訂單編號: {0}", ord["id"]);; string cAddress = ds.Tables[0].Rows[r]["地址"] ; Console.Write("\t數量:{1}\n", ord["qty"]); }Console.WriteLine("\n{0}\t{1}", cName, cAddress) ; } Data, XML, And .NET XML Recap • • • • • • XML declaration Document element <?xml version="1.0"?> Elements <employees xmlns="urn:…"> Attributes <employee id="123"> Text content <name>Philips</name> <salary>145000</salary> Namespaces </employee> … </employees> .NET XML Classes Namespaces and Classes System.Xml namespace • XmlReader XmlDocument XmlWriter XmlElement XmlNavigator XmlAttribute etc. Plus… System.Xml.XPath XPath engine System.Xml.Xsl XSLT transforms .NET XML Classes Reading XML Data • Use XmlReader class – Fast, forwards-only, read-only cursor – “Pull” model (not the “push” model of SAX) • XmlReader is an abstract class XmlReader { Abstract class } – Several concrete subclasses XmlTextReader XmlNodeReader Read a text-based stream Read an in-memory DOM tree .NET XML Classes Using XmlReader • Example XmlReader reader; reader = new XmlTextReader("MyFile.xml"); while(reader.Read()) { …process nodes… } • Capabilities – Pull nodes you want, skip those you don't – Get detailed node information – Get typed data .NET XML Classes Writing XML Data XmlWriter • Use XmlWriter XmlTextWriter XmlNodeWriter XmlWriter writer = new XmlTextWriter(…); writer.WriteStartDocument(); writer.WriteStartElement("name", "Mike"); • Alternatively… – Create content using XmlDocument – Serialise data using XmlWriter .NET XML Classes Using XPath • • XPath maps an XML document to a tree of nodes Use XPath expressions to identify, select, and manipulate nodes in an XML hierarchy – Use location paths to select nodes – XPath operators and functions .NET XML Classes XML .NET Support for XPath • XmlNavigator class provides XPath support XmlNavigator nav; nav = new DocumentNavigator(document); • Evaluate XPath expressions nav.Evaluate("count(//employee)"); • Select nodes using XPath nav.Select("//employee[salary > 75000]"); .NET XML Classes Using XSLT XML document XSLT processor + HTML document (XML-conformant) XSLT style sheet XML document + XSLT style sheet XSLT processor XML document (different grammar) .NET XML Classes XML .NET Support for XSLT • XslTransform class represents an XSLT style sheet // Load style sheet XslTransform xsl = new XslTransform(); xsl.Load("MyStylesheet.xsl"); // Perform transformation xsl.Transform(aNavigator, null, anXmlWriter); XML and ADO.NET Unified Architecture Controls, Designers, Code-gen, etc. XSL/T, X-Path, Validation, etc. XmlDataDocument XmlReader XmlTextReader XmlNodeReader DataSet Sync DataAdapter SqlData- OleDbDataAdapter Adapter DataReader SqlData- OleDbDataReader Reader