SlideShare a Scribd company logo
Cách sử dụ ng Data Readers                           Author : Xcross87   2007


Ở bàitrướcmìnhđãgiớithiệuvềcáchviết SQL statement vàthựcthi (execute)
câulệnh.Ở bàinàymìnhsẽtómtắtvềcácsửdụng Data Readers.

Data Readers đượcdùngđể :

         Thu nhậnkếtquảtừcác query
         Lấythông tin vềcáccộtcáchàngtrongbảngdữliệu
         Lấythông tin result set
         Lấythông tin về schema
         Xửlýcác result sets

Tổngquátvề Data Readers (Data Readers in General)

Thànhphầnthứbacủanhàcungcấpdữliệulà „data reader‟, 2 thànhphầntrướclà
„connection‟ và
„command‟.Mộtkhiđãtạođượckếtnốitớicơsởdữliệuvàthihànhcáclệnh querythìchúng
ta cầnmộtphươngthứcnàođóđểhỗtrợcáchxửlýdữliệuthunhậnđược.Nếubạnđãbiếtvề
ADO thìmột ADO.NET data reader giốngnhưlà ADO recordsetmộtchiềuphía client,
chứkhôngphảilàmộtđốitượng COM.

Data readerslàcácđốitượngđượccungcấptronglớp interface
„System.Data.IdataReader‟. Một „data reader‟ cóthểgọilàmột stream
đãkếtnốitớicơsởdữliệuđọcdữliệuhiệuquả,
theomộtchiềuvàthunhậndữliệutheotừngdòng (row).Vìvậykhôngthểtrựctiếpxửlý data
reader màphảixửlýthông qua phươngthức „ExecuteReader‟ củamộtđốitượng
command. Vídụ

[code]

SqlConnection conn = new SqlConnection(connectionString);

SqlCommandcmd = new SqlCommand(new string(“query command”), conn);

SqlDataReader reader = cmd.ExecuteReader();

[/code]

Đoạn code ở trênlà minh họacáchtạomộtđốitượngtronglớpSqlDataReader.



                                    Page 1 of 12
Cách sử dụ ng Data Readers                          Author : Xcross87   2007


Chú ý: Quytắcchungkhisửdụng data reader
dơngiảnlàchỉthunhậnvàtrìnhbàykếtquảthuđược.Phânbiệt data reader với dataset, cả
2
đềuđượctạoravớimụcđíchkhácnhaumặcdùcáchnhìnnhậnchungthìđềuthunhậnkếtquả.

Thửmộtvàivídụlàmviệcvới Data Reader

[code]
using System;
using System.Data;
using System.Data.SqlClient;

publicclassThiHanhMenhLenh
{
publicstaticvoid Main()
    {
// Tạo connection
SqlConnection conn = newSqlConnection(@"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 = newSqlCommand(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
        {

                                  Page 2 of 12
Cách sử dụ ng Data Readers                           Author : Xcross87   2007


// Đóng kết nối
            conn.Close();
Console.WriteLine("Close connection !");
        }
    }
}
[/code]

Trongvònglặpthukếtquảcủa „data reader‟ (reader) phươngthức„Read()‟
trỏđếngiátrịhàngtiếptheo(nếucó) . Bảnchấtkhi reader đãcókếtquảsaukhithựcthi
query thì reader nắmgiữtoànbộ record thuđược. vìvậycóthểdùng index
đểgọiđếnmộtgiátrịbấtkìtrongkếtquảthuđượcnằmtronggiớihạncủa bound.

Cuốicùngthìphảiđónglại reader.Tạisaođóng ?Vìkhiđãkếtnốivà reader
đượcgắnvàokếtnốithì reader sẽnằm ở
đóđểlấydữliệukhixửlý.Cứtưởngtượngmộtngôinhàmàchỉcóngườivàokhôngcóngườir
athìđếnmộtlúcnàođósẽkhôngvàođượcnữamàmuốnracũngkhôngđược.Tươngtựnhưvậ
y, phảiđónglại reader saumỗilầnđọc.

Vídụdướiđây minh họacáchsửdụng index gọigiátrị column khiRead()

[code]
using System;
using System.Data;
using System.Data.SqlClient;

publicclassThiHanhMenhLenh
{
publicstaticvoid Main()
    {
// Tạo connection
SqlConnection conn = newSqlConnection(@"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();

                                   Page 3 of 12
Cách sử dụ ng Data Readers                          Author : Xcross87   2007


// Tạo command
SqlCommand cmd = newSqlCommand(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ếtquảthuđượctrong reader thuvềlàkiểuobject .Vìvậy ở trênmình convert các
object sang kiểu string (ToString())
sauđócănlề.Cuốicùngđóngkếtnốiđểgiảiphóngkhỏikếtnối.

Nhiềulúccũngchẳngbiếtlàcộtsốmấyvịtrínàohơiphứctạp.LớpSqlDataReadercungcấpc
hođốitượngcáchchỉđịnh index bằngtêncột.

[code]

reader[“companyname”].ToString().PadLeft(25);

reader[“contactname”].ToString().PadLeft(20);

                                   Page 4 of 12
Cách sử dụ ng Data Readers                          Author : Xcross87   2007


[/code]

Tuynhiên 2
cáchtrênđềukhôngtốiưu.Vìkhitruycậpvàobảngdữliệukếtquảthuđượcgiữtạmthờitheo
kiểucủa .NET chứkhôngphảikiểu ban đầutrongtàinguyên.Haicách ở
trênmỗilầnlấymộtkếtquảđềukiểmtraxemdữliệukiểugìvà convert kiểunênkhôngtốiưu.

Do đóphươngthứclấydữliệutheokiểuđượccungcấp ,tấtcảbắtđầuvới „Get‟

Dướiđâylà 2 bảngdữliệutươngứngcáckiểudữliệutrongSQLServervà OLE DB
với .NET

Bảng1 :Kiểudữliệutrong SQL Server và .NET

      SQL Server                         .NET           Phươngthứctruycập
Bigint                         Int64                  GetInt64
Binary                         Byte[]                 GetBytes
Bit                            Boolean                GetBoolean
Char                           String hoặc Char[]     GetStringhoặcGetChars
Datetime                       DateTime               GetDateTime
Decimal                        Decimal                GetDecimal
Float                          Double                 GetDouble
Image hoặc long                Byte[]                 GetBytes
varbinary
Int                            Int32                  GetInt32
Money                          Decimal                GetDecimal
Nchar                          String hoặc Char[]     GetStringhoặcGetChars
Ntext                          String hoặc Char[]     GetStringhoặcGetChars
Numeric                        Decimal                GetDecimal
Nvarchar                       String hoặc Char[]     GetStringhoặcGetChars
Real                           Single                 GetFloat
Smalldatetime                  DateTime               GetDateTime
Smallint                       Inte16                 GetInt16
Smallmoney                     Decimal                GetDecimal
Sql_variant                    Object                 GetValue
Long varchar                   String hoặc Char[]     GetStringhoặcGetChars
Timestamp                      Byte[]                 GetBytes
Tinyint                        Byte                   GetByte
Uniqueidentifier               Guid                   GetGuid
                                       Page 5 of 12
Cách sử dụ ng Data Readers                           Author : Xcross87   2007


Varbinary                      Byte[]                  GetBytes
Varchar                        String hoặc Char[]      GetStringhoặcGetChars


Bảng2 :Kiểudữliệutrong OLE DB và .NET




       OLE DB                                .NET        Phươngthứctruycập
DBTYPE_I8                          Int64                GetInt64
DBTYPE_BYTES                       Byte[]               GetBytes
DBTYPE_BOOL                        Boolean              GetBoolean
DBTYPE_BSTR                        String               GetString
DBTYPE_STR                         String               GetString
DBTYPE_CY                          Decimal              GetDecimal
DBTYPE_DATE                        DateTime             GetDateTime
DBTYPE_DBDATE                      DateTime             GetDateTime
DBTYPE_DBTIME                      DateTime             GetDateTime
DBTYPE_DBTIMESTAMP                 DateTime             GetDateTime
DBTYPE_DECIMAL                     Decimal              GetDecimal
DBTYPE_R8                          Double               GetDouble
DBTYPE_ERROR                       ExternalException    GetValue
DBTYPE_FILETIME                    DateTime             GetDateTime
DBTYPE_GUID                        Guid                 GetGuid
DBTYPE_I4                          Int32                GetInt32
DBTYPE_LONGVARCHAR                 String               GetString
DBTYPE_NUMERIC                     Decimal              GetDecimal
DBTYPE_R4                          Single               GetFloat
DBTYPE_I2                          Int16                GetInt16
DBTYPE_I1                          Byte                 GetByte
DBTYPE_UI8                         Uint64               GetValue
DBTYPE_UI4                         Uint32               GetValue
DBTYPE_UI2                         Uint16               GetValue
DBTYPE_VARCHAR                     String               GetString
DBTYPE_VARIANT                     Object               GetValue
DBTYPE_NVARCHAR                    String               GetString
DBTYPE_WSRT                        String               GetString
                                       Page 6 of 12
Cách sử dụ ng Data Readers                                Author : Xcross87   2007




Vídụbảng Products trongNorthwind

                                                                         Cho phép
     Têncột                 Kiểudữliệu              Độdài
                                                                         NULLS?
ProductID             Int                   4                      No
(unique)
ProductName           Nvarchar              40                     No
SupplierID            Int                   4                      Yes
CategoryID            Int                   4                      Yes
QuantityPerUnit       Nvarchar              20                     Yes
UnitPrice             Money                 8                      Yes
UnitInStock           Smallint              2                      Yes
UnitsOnOrder          Smallint              2                      Yes
ReorderLevel          Smallint              2                      Yes
Discontinued          Bit                   1                      No


Dướiđâylàđoạn code minh họacáchsửdụngphươngthứctruycậptheokiểudữliệu :

[code]
using System;
using System.Data;
using System.Data.SqlClient;

publicclassThiHanhMenhLenh
{
publicstaticvoid Main()
    {
// Tạo connection
SqlConnection conn = newSqlConnection(@"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

                                     Page 7 of 12
Cách sử dụ ng Data Readers                     Author : Xcross87   2007


            conn.Open();
// Tạo command
SqlCommand cmd = newSqlCommand(sql, conn);

// Tạo Data Reader
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
            {
Console.WriteLine("{0}t{1}tt{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ấythông tin về Data

Vídụdướiđâylấythông tin về schema củabảng :

[code]
using System;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
publicclassDataReader
{
publicstaticvoid Main()
    {

                                  Page 8 of 12
Cách sử dụ ng Data Readers                  Author : Xcross87   2007


// Tạo connection
SqlConnection conn = newSqlConnection(@"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 = newSqlCommand(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 9 of 12
Cách sử dụ ng Data Readers                           Author : Xcross87   2007


Ở đâydùng „GetSchemaTable‟ đểlấyvềthông tin Schema,
nhưtêngọithìkếtquảtrảvềkiểuDataTable.Vìvậy ta
phảixửlýDataTablebằngDataRowvàDataColumn.

Bảngdướiđâylàcác method đượccungcấpđểlấythông tin vềdữliệu

      PhươngthứchoặcĐặctính                             Chúthích
Depth – ĐT                               Lấyđộsâucủa Row hiệntại
FieldCount – ĐT                          Sốlượngcộtcủa Row hiệntại
GetDataTypeName – PT                     Kiểudữliệucủa Col
GetFieldType – PT                        Kiểucủa Object trong .NET Framework
GetName – PT                             Têncủa Column hiệntại
GetOrdinal - PT                          Trảvề index của Column
                                         tươngứngvớitên
GetSchemaTable– PT                       Column Metadata
HasRows – ĐT                             Kiểmtra data reader có row hay không ?
RecordsAffected - ĐT                     Sốlượng Rows bịthayđổi, chènthêm, xóa


Xửlýnhiều result sets vớimột data reader

Vídụgọimộtlúcnhiều query vàmột data reader
thìviệcxửlýdữliệuthuđượcdườngnhưphứctạpnhưng .NET
cócungcấpmộtphươngthứcđểlàmviệcvớithaotácnày„NextResult()‟

Vídụdướiđây minh họathaotácxửlýnhiều result sets vớimột reader

[code]
using System;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
publicclassDataReader
{
publicstaticvoid Main()
    {
// Tạo connection
SqlConnection conn = newSqlConnection(@"Server = .SQLEXPRESS;
                                                 Integrated
Security = True;


                                  Page 10 of 12
Cách sử dụ ng Data Readers                         Author : Xcross87   2007


                                                          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 = newSqlCommand(sql, conn);

// Tạo Data Reader
SqlDataReader reader = cmd.ExecuteReader();
do
            {
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]

Ở đâycó 2 query vàtừng query đượcxửlýlầnlượt.Chú ý các query
phảicómộtkítựngăncáchđểkiểmtrahợplệ, trong SQL Server
thìđơngiảnchỉcầnmộtdấucách (space) làđược.

Kếtthúcvềsửdụng Data Readers.

                                 Page 11 of 12
Cách sử dụ ng Data Readers                   Author : Xcross87   2007




                             Page 12 of 12

More Related Content

DOCX
Cach su dung data reader
DOCX
6.adapterset
PDF
Aspnet 3.5 _02
PDF
Net06 asp.net applications & state management
DOCX
Cach su dung databinding
DOC
Thuc hanh ado.net_bai_03
DOC
Zend db
PDF
Hướng dẫn lập trình quản lý c#
Cach su dung data reader
6.adapterset
Aspnet 3.5 _02
Net06 asp.net applications & state management
Cach su dung databinding
Thuc hanh ado.net_bai_03
Zend db
Hướng dẫn lập trình quản lý c#

What's hot (20)

DOCX
Tổng hợp nè
ODP
Android Nâng cao-Bài 8-JSON & XML Parsing
PPT
04 chuong 4 - databinding
PPT
ado.net
PPT
Ung dung web chuong 6
PPTX
Nhibernate -Co ban
DOCX
Them,xoa,sua data trong xml
PPT
Bài 6: Working with DATA
PPTX
Linq2 sql
DOCX
Thuc thi menh lenh voi co so du lieu
PPTX
The Art of Readable Code - DongPV
PPTX
Data storage Android
PDF
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 winfor...
DOCX
4.thuc thi menh lenh voi co so du lieu
PDF
Chương 3 Ngôn ngữ truy vấn có cấu trúc (SQL)
DOC
Android report
PDF
Hdth08 ltudql02-linq
PDF
Lap trinhcosodulieuvoi c-sharp_phan-2
PDF
Hdth07 ltudql02-linq-ep1
PPT
03 chuong 3 - data sets
Tổng hợp nè
Android Nâng cao-Bài 8-JSON & XML Parsing
04 chuong 4 - databinding
ado.net
Ung dung web chuong 6
Nhibernate -Co ban
Them,xoa,sua data trong xml
Bài 6: Working with DATA
Linq2 sql
Thuc thi menh lenh voi co so du lieu
The Art of Readable Code - DongPV
Data storage Android
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 winfor...
4.thuc thi menh lenh voi co so du lieu
Chương 3 Ngôn ngữ truy vấn có cấu trúc (SQL)
Android report
Hdth08 ltudql02-linq
Lap trinhcosodulieuvoi c-sharp_phan-2
Hdth07 ltudql02-linq-ep1
03 chuong 3 - data sets
Ad

Similar to 5.cach su dung data reader (20)

PDF
Bài 5: Làm quen với lập trình CSDL ASP.NET - Giáo trình FPT - Có ví dụ kèm theo
PPT
PPT
Session 07 Final
PPT
PPT
Bài 3: Servlet - Lập Trình Mạng Nâng Cao
PPT
Ung dung web chuong 7
PDF
Tài liệu tìm hiểu jQuery dành cho người mới bắt đầu
PPTX
Lập trình web với các công nghệ phổ biến
PPT
Asp
PDF
Bai3 basic servlets_956
PDF
OOP_02_Java can ban.pdf
PPT
02 chuong 2 - lay du lieu theo cach connected
PPT
02 chuong2-laydulieutheocachconnected-140404114611-phpapp02
PPT
Chuong 07_ gắng kết dữ liệu asp.net
PPTX
LINQ presentation
DOCX
2.gioi thieu co ban ado.net cho nguoi lap trinh c#
PDF
Giao trinh java script
PPTX
Data mining - Luật kết hợp và ứng dụng
PDF
Bài 2: Biến và toán tử - Giáo trình FPT
Bài 5: Làm quen với lập trình CSDL ASP.NET - Giáo trình FPT - Có ví dụ kèm theo
Session 07 Final
Bài 3: Servlet - Lập Trình Mạng Nâng Cao
Ung dung web chuong 7
Tài liệu tìm hiểu jQuery dành cho người mới bắt đầu
Lập trình web với các công nghệ phổ biến
Asp
Bai3 basic servlets_956
OOP_02_Java can ban.pdf
02 chuong 2 - lay du lieu theo cach connected
02 chuong2-laydulieutheocachconnected-140404114611-phpapp02
Chuong 07_ gắng kết dữ liệu asp.net
LINQ presentation
2.gioi thieu co ban ado.net cho nguoi lap trinh c#
Giao trinh java script
Data mining - Luật kết hợp và ứng dụng
Bài 2: Biến và toán tử - Giáo trình FPT
Ad

5.cach su dung data reader

  • 1. Cách sử dụ ng Data Readers Author : Xcross87 2007 Ở bàitrướcmìnhđãgiớithiệuvềcáchviết SQL statement vàthựcthi (execute) câulệnh.Ở bàinàymìnhsẽtómtắtvềcácsửdụng Data Readers. Data Readers đượcdùngđể : Thu nhậnkếtquảtừcác query Lấythông tin vềcáccộtcáchàngtrongbảngdữliệu Lấythông tin result set Lấythông tin về schema Xửlýcác result sets Tổngquátvề Data Readers (Data Readers in General) Thànhphầnthứbacủanhàcungcấpdữliệulà „data reader‟, 2 thànhphầntrướclà „connection‟ và „command‟.Mộtkhiđãtạođượckếtnốitớicơsởdữliệuvàthihànhcáclệnh querythìchúng ta cầnmộtphươngthứcnàođóđểhỗtrợcáchxửlýdữliệuthunhậnđược.Nếubạnđãbiếtvề ADO thìmột ADO.NET data reader giốngnhưlà ADO recordsetmộtchiềuphía client, chứkhôngphảilàmộtđốitượng COM. Data readerslàcácđốitượngđượccungcấptronglớp interface „System.Data.IdataReader‟. Một „data reader‟ cóthểgọilàmột stream đãkếtnốitớicơsởdữliệuđọcdữliệuhiệuquả, theomộtchiềuvàthunhậndữliệutheotừngdòng (row).Vìvậykhôngthểtrựctiếpxửlý data reader màphảixửlýthông qua phươngthức „ExecuteReader‟ củamộtđốitượng command. Vídụ [code] SqlConnection conn = new SqlConnection(connectionString); SqlCommandcmd = new SqlCommand(new string(“query command”), conn); SqlDataReader reader = cmd.ExecuteReader(); [/code] Đoạn code ở trênlà minh họacáchtạomộtđốitượngtronglớpSqlDataReader. Page 1 of 12
  • 2. Cách sử dụ ng Data Readers Author : Xcross87 2007 Chú ý: Quytắcchungkhisửdụng data reader dơngiảnlàchỉthunhậnvàtrìnhbàykếtquảthuđược.Phânbiệt data reader với dataset, cả 2 đềuđượctạoravớimụcđíchkhácnhaumặcdùcáchnhìnnhậnchungthìđềuthunhậnkếtquả. Thửmộtvàivídụlàmviệcvới Data Reader [code] using System; using System.Data; using System.Data.SqlClient; publicclassThiHanhMenhLenh { publicstaticvoid Main() { // Tạo connection SqlConnection conn = newSqlConnection(@"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 = newSqlCommand(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 { Page 2 of 12
  • 3. Cách sử dụ ng Data Readers Author : Xcross87 2007 // Đóng kết nối conn.Close(); Console.WriteLine("Close connection !"); } } } [/code] Trongvònglặpthukếtquảcủa „data reader‟ (reader) phươngthức„Read()‟ trỏđếngiátrịhàngtiếptheo(nếucó) . Bảnchấtkhi reader đãcókếtquảsaukhithựcthi query thì reader nắmgiữtoànbộ record thuđược. vìvậycóthểdùng index đểgọiđếnmộtgiátrịbấtkìtrongkếtquảthuđượcnằmtronggiớihạncủa bound. Cuốicùngthìphảiđónglại reader.Tạisaođóng ?Vìkhiđãkếtnốivà reader đượcgắnvàokếtnốithì reader sẽnằm ở đóđểlấydữliệukhixửlý.Cứtưởngtượngmộtngôinhàmàchỉcóngườivàokhôngcóngườir athìđếnmộtlúcnàođósẽkhôngvàođượcnữamàmuốnracũngkhôngđược.Tươngtựnhưvậ y, phảiđónglại reader saumỗilầnđọc. Vídụdướiđây minh họacáchsửdụng index gọigiátrị column khiRead() [code] using System; using System.Data; using System.Data.SqlClient; publicclassThiHanhMenhLenh { publicstaticvoid Main() { // Tạo connection SqlConnection conn = newSqlConnection(@"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(); Page 3 of 12
  • 4. Cách sử dụ ng Data Readers Author : Xcross87 2007 // Tạo command SqlCommand cmd = newSqlCommand(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ếtquảthuđượctrong reader thuvềlàkiểuobject .Vìvậy ở trênmình convert các object sang kiểu string (ToString()) sauđócănlề.Cuốicùngđóngkếtnốiđểgiảiphóngkhỏikếtnối. Nhiềulúccũngchẳngbiếtlàcộtsốmấyvịtrínàohơiphứctạp.LớpSqlDataReadercungcấpc hođốitượngcáchchỉđịnh index bằngtêncột. [code] reader[“companyname”].ToString().PadLeft(25); reader[“contactname”].ToString().PadLeft(20); Page 4 of 12
  • 5. Cách sử dụ ng Data Readers Author : Xcross87 2007 [/code] Tuynhiên 2 cáchtrênđềukhôngtốiưu.Vìkhitruycậpvàobảngdữliệukếtquảthuđượcgiữtạmthờitheo kiểucủa .NET chứkhôngphảikiểu ban đầutrongtàinguyên.Haicách ở trênmỗilầnlấymộtkếtquảđềukiểmtraxemdữliệukiểugìvà convert kiểunênkhôngtốiưu. Do đóphươngthứclấydữliệutheokiểuđượccungcấp ,tấtcảbắtđầuvới „Get‟ Dướiđâylà 2 bảngdữliệutươngứngcáckiểudữliệutrongSQLServervà OLE DB với .NET Bảng1 :Kiểudữliệutrong SQL Server và .NET SQL Server .NET Phươngthứctruycập Bigint Int64 GetInt64 Binary Byte[] GetBytes Bit Boolean GetBoolean Char String hoặc Char[] GetStringhoặcGetChars Datetime DateTime GetDateTime Decimal Decimal GetDecimal Float Double GetDouble Image hoặc long Byte[] GetBytes varbinary Int Int32 GetInt32 Money Decimal GetDecimal Nchar String hoặc Char[] GetStringhoặcGetChars Ntext String hoặc Char[] GetStringhoặcGetChars Numeric Decimal GetDecimal Nvarchar String hoặc Char[] GetStringhoặcGetChars Real Single GetFloat Smalldatetime DateTime GetDateTime Smallint Inte16 GetInt16 Smallmoney Decimal GetDecimal Sql_variant Object GetValue Long varchar String hoặc Char[] GetStringhoặcGetChars Timestamp Byte[] GetBytes Tinyint Byte GetByte Uniqueidentifier Guid GetGuid Page 5 of 12
  • 6. Cách sử dụ ng Data Readers Author : Xcross87 2007 Varbinary Byte[] GetBytes Varchar String hoặc Char[] GetStringhoặcGetChars Bảng2 :Kiểudữliệutrong OLE DB và .NET OLE DB .NET Phươngthứctruycập DBTYPE_I8 Int64 GetInt64 DBTYPE_BYTES Byte[] GetBytes DBTYPE_BOOL Boolean GetBoolean DBTYPE_BSTR String GetString DBTYPE_STR String GetString DBTYPE_CY Decimal GetDecimal DBTYPE_DATE DateTime GetDateTime DBTYPE_DBDATE DateTime GetDateTime DBTYPE_DBTIME DateTime GetDateTime DBTYPE_DBTIMESTAMP DateTime GetDateTime DBTYPE_DECIMAL Decimal GetDecimal DBTYPE_R8 Double GetDouble DBTYPE_ERROR ExternalException GetValue DBTYPE_FILETIME DateTime GetDateTime DBTYPE_GUID Guid GetGuid DBTYPE_I4 Int32 GetInt32 DBTYPE_LONGVARCHAR String GetString DBTYPE_NUMERIC Decimal GetDecimal DBTYPE_R4 Single GetFloat DBTYPE_I2 Int16 GetInt16 DBTYPE_I1 Byte GetByte DBTYPE_UI8 Uint64 GetValue DBTYPE_UI4 Uint32 GetValue DBTYPE_UI2 Uint16 GetValue DBTYPE_VARCHAR String GetString DBTYPE_VARIANT Object GetValue DBTYPE_NVARCHAR String GetString DBTYPE_WSRT String GetString Page 6 of 12
  • 7. Cách sử dụ ng Data Readers Author : Xcross87 2007 Vídụbảng Products trongNorthwind Cho phép Têncột Kiểudữliệu Độdài NULLS? ProductID Int 4 No (unique) ProductName Nvarchar 40 No SupplierID Int 4 Yes CategoryID Int 4 Yes QuantityPerUnit Nvarchar 20 Yes UnitPrice Money 8 Yes UnitInStock Smallint 2 Yes UnitsOnOrder Smallint 2 Yes ReorderLevel Smallint 2 Yes Discontinued Bit 1 No Dướiđâylàđoạn code minh họacáchsửdụngphươngthứctruycậptheokiểudữliệu : [code] using System; using System.Data; using System.Data.SqlClient; publicclassThiHanhMenhLenh { publicstaticvoid Main() { // Tạo connection SqlConnection conn = newSqlConnection(@"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 Page 7 of 12
  • 8. Cách sử dụ ng Data Readers Author : Xcross87 2007 conn.Open(); // Tạo command SqlCommand cmd = newSqlCommand(sql, conn); // Tạo Data Reader SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Console.WriteLine("{0}t{1}tt{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ấythông tin về Data Vídụdướiđâylấythông tin về schema củabảng : [code] using System; using System.Data; using System.Data.SqlClient; using System.Xml; publicclassDataReader { publicstaticvoid Main() { Page 8 of 12
  • 9. Cách sử dụ ng Data Readers Author : Xcross87 2007 // Tạo connection SqlConnection conn = newSqlConnection(@"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 = newSqlCommand(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 9 of 12
  • 10. Cách sử dụ ng Data Readers Author : Xcross87 2007 Ở đâydùng „GetSchemaTable‟ đểlấyvềthông tin Schema, nhưtêngọithìkếtquảtrảvềkiểuDataTable.Vìvậy ta phảixửlýDataTablebằngDataRowvàDataColumn. Bảngdướiđâylàcác method đượccungcấpđểlấythông tin vềdữliệu PhươngthứchoặcĐặctính Chúthích Depth – ĐT Lấyđộsâucủa Row hiệntại FieldCount – ĐT Sốlượngcộtcủa Row hiệntại GetDataTypeName – PT Kiểudữliệucủa Col GetFieldType – PT Kiểucủa Object trong .NET Framework GetName – PT Têncủa Column hiệntại GetOrdinal - PT Trảvề index của Column tươngứngvớitên GetSchemaTable– PT Column Metadata HasRows – ĐT Kiểmtra data reader có row hay không ? RecordsAffected - ĐT Sốlượng Rows bịthayđổi, chènthêm, xóa Xửlýnhiều result sets vớimột data reader Vídụgọimộtlúcnhiều query vàmột data reader thìviệcxửlýdữliệuthuđượcdườngnhưphứctạpnhưng .NET cócungcấpmộtphươngthứcđểlàmviệcvớithaotácnày„NextResult()‟ Vídụdướiđây minh họathaotácxửlýnhiều result sets vớimột reader [code] using System; using System.Data; using System.Data.SqlClient; using System.Xml; publicclassDataReader { publicstaticvoid Main() { // Tạo connection SqlConnection conn = newSqlConnection(@"Server = .SQLEXPRESS; Integrated Security = True; Page 10 of 12
  • 11. Cách sử dụ ng Data Readers Author : Xcross87 2007 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 = newSqlCommand(sql, conn); // Tạo Data Reader SqlDataReader reader = cmd.ExecuteReader(); do { 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] Ở đâycó 2 query vàtừng query đượcxửlýlầnlượt.Chú ý các query phảicómộtkítựngăncáchđểkiểmtrahợplệ, trong SQL Server thìđơngiảnchỉcầnmộtdấucách (space) làđược. Kếtthúcvềsửdụng Data Readers. Page 11 of 12
  • 12. Cách sử dụ ng Data Readers Author : Xcross87 2007 Page 12 of 12