相關(guān)知識(shí):
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
代碼示例:
using System.Data;using System.Data.SqlClient;using System.IO;
1 const int BUF_SIZE = 1024;//緩沖區(qū)大小2 static string strConn = @"server=Joe-PC;database=AdventureWorks_WroxSSRS2012;uid=sa;pwd=root";3 static SqlConnection conn = new SqlConnection(strConn);4 //優(yōu)先把BLOB字段前的其他字段讀取出來(lái),否則一旦開(kāi)始讀BLOB字段,將無(wú)法再回頭去讀之前的字段(注意此sql語(yǔ)句中字段的順序與數(shù)據(jù)庫(kù)字段順序的對(duì)比)5 static string strCmd = "SELECT ProductPhotoID,ThumbnailPhotoFileName,ThumbNailPhoto,LargePhotoFileName,LargePhoto FROM Production.ProductPhoto";6 static SqlCommand cmd = new SqlCommand(strCmd, conn);
1 static void Main(string[] args) 2 { 3 try 4 { 5 conn.Open(); 6 //以SequentialAccesss方式打開(kāi)DataReader 7 SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SequentialAccess); 8 while (dr.Read()) 9 {10 int productPhotoID = dr.GetInt32(0);11 string thumbnailPhotoFileName = dr.GetString(1);//讀取縮略圖文件名12 WriteThumbnailPhotoFile(thumbnailPhotoFileName, dr);//將縮略圖二進(jìn)制數(shù)據(jù)寫(xiě)入磁盤(pán)文件13 string largePhotoFileName = dr.GetString(3);//讀取大圖文件名14 WriteLargePhotoFile(largePhotoFileName, dr);//將大圖二進(jìn)制數(shù)據(jù)寫(xiě)入磁盤(pán)文件15 }16 }17 catch (Exception e)18 {19 Console.WriteLine(e);20 }21 finally22 {23 conn.Close();24 }25 }
1 static void WriteThumbnailPhotoFile(string fileName, SqlDataReader dr)2 {3 string path = "..//..//images//Thumbnail//" + fileName;//需要預(yù)先在項(xiàng)目文件夾中建立此目錄4 FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write);5 //ThumbnailPhoto的數(shù)據(jù)比較小(沒(méi)有超過(guò)8KB),因此選擇一次性讀出,直接寫(xiě)入文件6 byte[] buf = dr[2] as byte[];7 fs.Write(buf, 0, buf.Length);8 fs.Close();9 }
1 static void WriteLargePhotoFile(string fileName, SqlDataReader dr) 2 { 3 string path = "..//..//images//Large//" + fileName;//需要預(yù)先在項(xiàng)目文件夾中建立此目錄 4 FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write); 5 byte[] buf = new byte[BUF_SIZE]; 6 long bytesRead = 0; 7 long startIndex = 0; 8 //LargePhoto的數(shù)據(jù)比較大,因此分批次讀出,分別寫(xiě)入文件 9 while ((bytesRead = dr.GetBytes(4, startIndex, buf, 0, BUF_SIZE)) > 0)10 {11 fs.Write(buf, 0, (int)bytesRead);12 startIndex += bytesRead;13 }14 fs.Close();15 }
程序說(shuō)明:
需要預(yù)先在本項(xiàng)目文件夾下建立images目錄,內(nèi)有thumbnail和large子目錄,用于存放從數(shù)據(jù)庫(kù)獲取的圖片
新聞熱點(diǎn)
疑難解答
圖片精選