連接ADO.NET數(shù)據(jù)庫注意事宜及技巧
雖然有許多人對ADO.NET數(shù)據(jù)庫的安全性表示懷疑,但在年復一年的不斷發(fā)展中,他的安全性也在不斷提高。保障ADO.NET數(shù)據(jù)庫的安全性是完全有可能的,但前提是要深入理解到底什么是ADO.NET數(shù)據(jù)庫,及他是怎么運作的。
使用ADO.NET數(shù)據(jù)庫的Datareader對象能從數(shù)據(jù)庫中檢索數(shù)據(jù)。檢索出來的數(shù)據(jù)形成一個只讀只進的數(shù)據(jù)流,存儲在客戶端的網(wǎng)絡(luò)緩沖區(qū)內(nèi)。ADO.NET數(shù)據(jù)庫的read方法可以前進到一下條記錄。在默認情況下,每執(zhí)行一次read方法只會在內(nèi)存中存儲一條記錄系統(tǒng)的開銷非常少。#t#
創(chuàng)建datareader之前必須先創(chuàng)建sqlcommand對象,然后調(diào)用該對象的executereader方法來構(gòu)造sqldatareader對象,下面的示例程序完成的功能是訪問ADO.NET數(shù)據(jù)庫,并使用datareader從northwind數(shù)據(jù)中讀取記錄,并將查詢結(jié)果通過控制臺輸出。
- using System;
- using System.Data;
- using System.Data.SqlClient;
- namespace ReadDataFromDB{
- class Class1{
- static void Main(string[] args){
- string myconn="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind";
- 需要執(zhí)行的SQL語句
- string mysql="select OrderID,CustomerID from Orders where CustomerID='CHOPS'";
- 打開數(shù)據(jù)庫連接。
- SqlConnection myconnection=new SqlConnection(myconn);
- myconnection.Open();
- 創(chuàng)建SqlCommand 對象
- SqlCommand mycommand=new(mysql,myconnection);
- 通過SqlCommand的ExecuteReader()方法構(gòu)造DataReader 對象。
- SqlDataReader myreader=mycommand.ExecuteReader();
- while(myreader.read()){
- Console.WriteLine(myreader.GetInt32(0)+","+myreader.GetString(1));
- }
- myreader.Close();
- myconnection.Close();
- }
- }
- }