很多時候,用手寫的方式,以 DataReader來列出資料,又快又好用。

相信大家都用的到。

 

以下的範例,只能用在「查詢」上面,也就是對應 SQL指令的「Select」陳述句

倘若您要作新增(Insert Into)、刪除(Delete)、修改(Update),不可以直接套用以下範例。
 

以下是我在微軟SDK文件找到的範本,寫得很標準~

這裡提供兩個版本,第一個版本是採用「 Try....Catch....Finally」等偵錯過程(VB.NET語法解說,抄起來放在手邊一定用的到。

不瞞您說,我衷心推薦微軟這份官方文件(資料和ADO.NET),是介紹最好、最淺顯的文章了!

 

 '=========資料來源:微軟SDK文件=========
ADO.NET:從 SQL Server 擷取資料

http://cht.gotdotnet.com/quickstart/howto/doc/adoplus/sqldtreader.aspx

範例 Northwind 資料庫的  Employees 資料表
'=================================

完整程式碼請看---- http://cht.gotdotnet.com/quickstart/util/srcview.aspx?path=/quickstart/howto/samples/adoplus/sqldtreader/sqldtreader.srca
 

 '--完全手寫程式,HTML畫面上,不需要拉進任何元件

Imports System
Imports System.Data
Imports System.Data.SqlClient

    Dim dr as SqlDataReader
    Dim Conn as SqlConnection = New SqlConnection("資料庫的連線字串,請自己修改")
    Dim cmd as SqlCommand = New SqlCommand("SELECT * from 資料表", Conn)

    try
      Conn.Open()
      dr = cmd.ExecuteReader()

      do while (dr.Read())
           '--把資料展現到畫面上。這一區請您請自由發揮
      loop

    catch e as Exception
         Response.Write(e.ToString())

    finally
         if Not (dr is Nothing ' --關閉 DataReader

             cmd.Cancel()   '--自己補上的,原因在下面有講。
             dr.Close()
         end if
     
         if (Conn.State = ConnectionState.Open)   ' --關閉 DB的連線
             Conn.Close()
         end if
    end try

註:上面的範例,我有改成C#語法,請看-- [C#]把「ASP.NET專題實務」一書的範例,從 VB語法轉成C#

 



第二個版本是採用「Using....End Using」VB.NET語法解說),抄起來放在手邊一定用的到。

根據微軟文件的說法,End Using的用法,是結束 Using 區塊的定義,並處置 (Dispose) 它控制的所有資源。

Imports System
Imports System.Data
Imports System.Data.SqlClient


    Using Conn As New SqlConnection("資料庫的連線字串")
        Dim cmd As New SqlCommand("SELECT * From 資料表", Conn)
        Conn.Open()  
        '-- 資料庫連線!
        '-- 但後面「」需要寫關閉的動作(Conn.Close()),因為Using....End Using 會自己處理

        Dim dr As SqlDataReader = cmd.ExecuteReader()

        While dr.Read()
               '-- 自己寫程式,展現欄位的值。這一區請您請自由發揮
        End While

        '-- 關閉DataReader
        cmd.Cancel()   '--我自己補上的,原因在下面有講。
        dr.Close()
    End Using
使用Using來寫程式的人,最好看看這篇文章的解釋:http://forums.microsoft.com/MSDN-CHT/ShowPost.aspx?PostID=1417995&SiteID=14
 

 


看看下面的說明,我們還是可以進一步最佳化!

DbDataReader.Dispose() 方法 -- 釋放 DbDataReader所使用的資源,並呼叫 .Close()方法。

務必先關閉 SqlCommand之後(執行 .Cancel()方法),再來關閉 DataReader,請看:http://msdn.microsoft.com/zh-tw/library/system.data.sqlclient.sqldatareader.close.aspx


 

 資料來源:微軟MSDN網站--  IDataReader 介面 http://msdn2.microsoft.com/zh-tw/library/system.data.idatareader.aspx

=======================================================================================

 

如果上面的 DataReader,您要使用「 參 數 」來作,以避免初步的SQL Injection(資料隱碼)攻擊

請稍作修改如下:

            '**** 重 點!*************************************************
            '**** 改用 SqlCommand @參數來作

            Dim cmd As New SqlCommand("select * from test where id = @id", Conn)

            cmd.Parameters.Add("@id", SqlDbType.Int)
            cmd.Parameters("@id").Value = CType(Request("id"), Integer)


            '== 參考網址  http://msdn.microsoft.com/zh-tw/library/system.data.sqlclient.sqlcommand.parameters.aspx
            '************************************************************

=======================================================================================

如果您想要使用 DataReader  撰寫「新增、刪除、修改」的動作,
需要使用 Command的 .NonExecuteQuery( )方法

請您參考這篇文章:  http://mis2000lab.pixnet.net/blog/post/34921282

arrow
arrow

    MIS2000 Lab 發表在 痞客邦 留言(0) 人氣()