1. Trang chủ
  2. » Công Nghệ Thông Tin

Cachsudungdatareader 130806045252 phpapp01

9 2 0

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Nội dung

Cách sử dụng Data Readers Author Xcross87 2007 Page 1 of 9 Ở bài trước mình đã giới thiệu về cách viết SQL statement và thực thi (execute) câu lệnh Ở bài này mình sẽ tóm tắt về các sử dụng Data Reader[.]

Cách sử dụng Data Readers Author : Xcross87 2007 Ở trước giới thiệu cách viết SQL statement thực thi (execute) câu lệnh Ở tóm tắt sử dụng Data Readers Data Readers dùng để : Thu nhận kết từ query Lấy thông tin cột hàng bảng liệu Lấy thông tin result set Lấy thông tin schema Xử lý result sets Tổng quát Data Readers (Data Readers in General) Thành phần thứ ba nhà cung cấp liệu „data reader‟, thành phần trước „connection‟ „command‟ Một tạo kết nối tới sở liệu thi hành lệnh query cần phương thức để hỗ trợ cách xử lý liệu thu nhận Nếu bạn biết ADO ADO.NET data reader giống ADO recordset chiều phía client, khơng phải đối tượng COM Data readers đối tượng cung cấp lớp interface „System.Data.IdataReader‟ Một „data reader‟ gọi stream kết nối tới sở liệu đọc liệu hiệu quả, theo chiều thu nhận liệu theo dịng (row).Vì khơng thể trực tiếp xử lý data reader mà phải xử lý thông qua phương thức „ExecuteReader‟ đối tượng command Ví dụ [code] SqlConnection conn = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(new string(“query command”), conn); SqlDataReader reader = cmd.ExecuteReader(); [/code] Đoạn code minh họa cách tạo đối tượng lớp SqlDataReader Chú ý: Quy tắc chung sử dụng data reader dơn giản thu nhận trình bày kết thu được.Phân biệt data reader với dataset, tạo với mục đích khác cách nhìn nhận chung thu nhận kết Thử vài ví dụ làm việc với Data Reader [code] using System; using System.Data; using System.Data.SqlClient; public class ThiHanhMenhLenh { Page of Cách sử dụng Data Readers Author : Xcross87 2007 public static void Main() { // Tạo connection SqlConnection conn = new SqlConnection(@"Server = \SQLEXPRESS; Integrated Security = True; Database = Northwind"); // Tạo query string sql = @"SELECT contactname FROM customers"; try { // Mở kết nối conn.Open(); // Tạo command SqlCommand cmd = new SqlCommand(sql, conn); // Tạo Data Reader SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Console.WriteLine(" {0} ", reader[0]); } reader.Close(); } catch (SqlException sqle) { // Thông báo lỗi Console.WriteLine(sqle.ToString()); } finally { // Đóng kết nối conn.Close(); Console.WriteLine("Close connection !"); } } } [/code] Trong vòng lặp thu kết „data reader‟ (reader) phương thức „Read()‟ trỏ đến giá trị hàng (nếu có) Bản chất reader có kết sau thực thi query reader nắm giữ tồn record thu dùng index để gọi đến giá trị kết thu nằm giới hạn bound Cuối phải đóng lại reader Tại đóng ? Vì kết nối reader gắn vào kết nối reader nằm để lấy liệu xử lý Cứ tưởng tượng nhà mà có người vào khơng có người đến lúc khơng vào mà muốn không Tương tự vậy, phải đóng lại reader sau lần đọc Ví dụ minh họa cách sử dụng index gọi giá trị column Read() [code] using System; using System.Data; using System.Data.SqlClient; Page of Cách sử dụng Data Readers Author : Xcross87 2007 public class ThiHanhMenhLenh { public static void Main() { // Tạo connection SqlConnection conn = new SqlConnection(@"Server = \SQLEXPRESS; Integrated Security = True; Database = Northwind"); // Tạo query string sql = @"SELECT companyname,contactname FROM customers WHERE contactname LIKE 'M%'"; try { // Mở kết nối conn.Open(); // Tạo command SqlCommand cmd = new SqlCommand(sql, conn); // In headings Console.WriteLine("\t{0} {1}", "Company Name".PadRight(25), "Contact Name".PadRight(20)); Console.WriteLine("\t{0} {1}", "============".PadRight(25), "============".PadRight(20)); // Tạo Data Reader SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Console.WriteLine("{0} | {1}", reader[0].ToString().PadLeft(25),reader[1].ToString().PadLeft(20)); } reader.Close(); } catch (SqlException sqle) { // Thông báo lỗi Console.WriteLine(sqle.ToString()); } finally { // Đóng kết nối conn.Close(); Console.WriteLine("Close connection !"); } } } [/code] Kết thu reader thu kiểu object Vì convert object sang kiểu string (ToString()) sau lề Cuối đóng kết nối để giải phóng khỏi kết nối Nhiều lúc chẳng biết cột số vị trí phức tạp Lớp SqlDataReader cung cấp cho đối tượng cách định index tên cột [code] Page of Cách sử dụng Data Readers Author : Xcross87 2007 reader[“companyname”].ToString().PadLeft(25); reader[“contactname”].ToString().PadLeft(20); [/code] Tuy nhiên cách khơng tối ưu Vì truy cập vào bảng liệu kết thu giữ tạm thời theo kiểu NET kiểu ban đầu tài nguyên Hai cách lần lấy kết kiểm tra xem liệu kiểu convert kiểu nên khơng tối ưu Do phương thức lấy liệu theo kiểu cung cấp , tất bắt đầu với „Get‟ Dưới bảng liệu tương ứng kiểu liệu SQLServer OLE DB với NET Bảng : Kiểu liệu SQL Server NET SQL Server Bigint Binary Bit Char Datetime Decimal Float Image long varbinary Int Money Nchar Ntext Numeric Nvarchar Real Smalldatetime Smallint Smallmoney Sql_variant Long varchar Timestamp Tinyint Uniqueidentifier Varbinary Varchar NET Int64 Byte[] Boolean String Char[] DateTime Decimal Double Byte[] Int32 Decimal String Char[] String Char[] Decimal String Char[] Single DateTime Inte16 Decimal Object String Char[] Byte[] Byte Guid Byte[] String Char[] Bảng : Kiểu liệu OLE DB NET Page of Phương thức truy cập GetInt64 GetBytes GetBoolean GetString GetChars GetDateTime GetDecimal GetDouble GetBytes GetInt32 GetDecimal GetString GetChars GetString GetChars GetDecimal GetString GetChars GetFloat GetDateTime GetInt16 GetDecimal GetValue GetString GetChars GetBytes GetByte GetGuid GetBytes GetString GetChars Cách sử dụng Data Readers OLE DB DBTYPE_I8 DBTYPE_BYTES DBTYPE_BOOL DBTYPE_BSTR DBTYPE_STR DBTYPE_CY DBTYPE_DATE DBTYPE_DBDATE DBTYPE_DBTIME DBTYPE_DBTIMESTAMP DBTYPE_DECIMAL DBTYPE_R8 DBTYPE_ERROR DBTYPE_FILETIME DBTYPE_GUID DBTYPE_I4 DBTYPE_LONGVARCHAR DBTYPE_NUMERIC DBTYPE_R4 DBTYPE_I2 DBTYPE_I1 DBTYPE_UI8 DBTYPE_UI4 DBTYPE_UI2 DBTYPE_VARCHAR DBTYPE_VARIANT DBTYPE_NVARCHAR DBTYPE_WSRT Author : Xcross87 2007 Phương thức truy cập GetInt64 GetBytes GetBoolean GetString GetString GetDecimal GetDateTime GetDateTime GetDateTime GetDateTime GetDecimal GetDouble GetValue GetDateTime GetGuid GetInt32 GetString GetDecimal GetFloat GetInt16 GetByte GetValue GetValue GetValue GetString GetValue GetString GetString NET Int64 Byte[] Boolean String String Decimal DateTime DateTime DateTime DateTime Decimal Double ExternalException DateTime Guid Int32 String Decimal Single Int16 Byte Uint64 Uint32 Uint16 String Object String String Ví dụ bảng Products Northwind Tên cột ProductID (unique) ProductName SupplierID CategoryID QuantityPerUnit UnitPrice UnitInStock UnitsOnOrder ReorderLevel Discontinued Kiểu liệu Int Nvarchar Int Int Nvarchar Money Smallint Smallint Smallint Bit Độ dài 40 4 20 2 Cho phép NULLS? No No Yes Yes Yes Yes Yes Yes Yes No Dưới đoạn code minh họa cách sử dụng phương thức truy cập theo kiểu liệu : Page of Cách sử dụng Data Readers Author : Xcross87 2007 [code] using System; using System.Data; using System.Data.SqlClient; public class ThiHanhMenhLenh { public static void Main() { // Tạo connection SqlConnection conn = new SqlConnection(@"Server = \SQLEXPRESS; Integrated Security = True; Database = Northwind"); // Tạo query string sql = @"SELECT productname, unitprice, unitsinstock, discontinued FROM products"; try { // Mở kết nối conn.Open(); // Tạo command SqlCommand cmd = new SqlCommand(sql, conn); // Tạo Data Reader SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Console.WriteLine("{0}\t{1}\t\t{2}\t{3}", reader.GetString(0).PadRight(30), reader.GetDecimal(1).ToString().PadLeft(8), reader.GetInt16(2), reader.GetBoolean(3)); } reader.Close(); } catch (SqlException sqle) { // Thơng báo lỗi Console.WriteLine(sqle.ToString()); } finally { // Đóng kết nối conn.Close(); Console.WriteLine("Close connection !"); } } } [/code] Lấy thơng tin Data Ví dụ lấy thông tin schema bảng : Page of Cách sử dụng Data Readers Author : Xcross87 2007 [code] using System; using System.Data; using System.Data.SqlClient; using System.Xml; public class DataReader { public static void Main() { // Tạo connection SqlConnection conn = new SqlConnection(@"Server = \SQLEXPRESS; Integrated Security = True; Database = Northwind"); // Tạo query string sql = @"SELECT productname, unitprice, unitsinstock, discontinued FROM products"; try { // Mở kết nối conn.Open(); // Tạo command SqlCommand cmd = new SqlCommand(sql, conn); // Tạo Data Reader SqlDataReader reader = cmd.ExecuteReader(); DataTable table = reader.GetSchemaTable(); foreach (DataRow row in table.Rows) { foreach (DataColumn col in table.Columns) { Console.WriteLine("{0} = {1}", col.ColumnName, row[col]); } Console.WriteLine("==========================="); } reader.Close(); } catch (SqlException sqle) { // Thông báo lỗi Console.WriteLine(sqle.ToString()); } finally { // Đóng kết nối conn.Close(); Console.WriteLine("Close connection !"); } } } [/code] Page of Cách sử dụng Data Readers Author : Xcross87 2007 Ở dùng „GetSchemaTable‟ để lấy thơng tin Schema, tên gọi kết trả kiểu DataTable Vì ta phải xử lý DataTable DataRow DataColumn Bảng method cung cấp để lấy thông tin liệu Phương thức Đặc tính Depth – ĐT FieldCount – ĐT GetDataTypeName – PT GetFieldType – PT GetName – PT GetOrdinal - PT GetSchemaTable – PT HasRows – ĐT RecordsAffected - ĐT Chú thích Lấy độ sâu Row Số lượng cột Row Kiểu liệu Col Kiểu Object NET Framework Tên Column Trả index Column tương ứng với tên Column Metadata Kiểm tra data reader có row hay khơng ? Số lượng Rows bị thay đổi, chèn thêm, xóa Xử lý nhiều result sets với data reader Ví dụ gọi lúc nhiều query data reader việc xử lý liệu thu dường phức tạp NET có cung cấp phương thức để làm việc với thao tác „NextResult()‟ Ví dụ minh họa thao tác xử lý nhiều result sets với reader [code] using System; using System.Data; using System.Data.SqlClient; using System.Xml; public class DataReader { public static void Main() { // Tạo connection SqlConnection conn = new SqlConnection(@"Server = \SQLEXPRESS; Integrated Security = True; Database = Northwind"); // Tạo query string sql1 = @"SELECT productname, unitprice FROM products "; string sql2 = @"SELECT firstname, lastname FROm employees "; string sql = sql1 + sql2; try { // Mở kết nối conn.Open(); // Tạo command SqlCommand cmd = new SqlCommand(sql, conn); // Tạo Data Reader SqlDataReader reader = cmd.ExecuteReader(); { Page of Cách sử dụng Data Readers Author : Xcross87 2007 while (reader.Read()) { Console.WriteLine("\t{0} - {1}", reader[0], reader[1]); } Console.WriteLine("".PadLeft(60,'=')); } while (reader.NextResult()); reader.Close(); } catch (SqlException sqle) { // Thơng báo lỗi Console.WriteLine(sqle.ToString()); } finally { // Đóng kết nối conn.Close(); Console.WriteLine("Close connection !"); } } } [/code] Ở có query query xử lý Chú ý query phải có kí tự ngăn cách để kiểm tra hợp lệ, SQL Server đơn giản cần dấu cách (space) Kết thúc sử dụng Data Readers Page of

Ngày đăng: 09/04/2023, 06:27

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN

w