C#存儲BLOB對象分析
學(xué)習(xí)C#語言時,經(jīng)常會遇到C#存儲BLOB對象問題,這里將介紹C#存儲BLOB對象問題的解決方法。
C#存儲BLOB對象
檢索和C#存儲BLOB對象是一個很簡單的過程;相反的過程,在 SQL Server 中C#存儲BLOB對象,也一樣簡單。這里我要指出的是,前面的例子中使用了由這個例子中的代碼存儲到表中的 BLOB 數(shù)據(jù)
- SqlConnection conn =null;
- SqlCommand cmd = null;
- SqlParameter param = null;
- FileStream fs = null;
- const string sConn = "server=(local);Initial
- Catalog=Northwind;UID=ctester;PWD=password";
- try {
- conn = new SqlConnection(sConn);
- cmd = new SqlCommand("UPDATE Categories SET Picture = @Picture WHERE
- CategoryName = 'Seafood'", conn);
- fs = new FileStream("c:\\Builder.doc", FileMode.Open, FileAccess.Read);
- Byte[] blob = new Byte[fs.Length];
- fs.Read(blob, 0, blob.Length);
- fs.Close();
- param = new SqlParameter("@Picture", SqlDbType.VarBinary, blob.Length,
- ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, blob);
- cmd.Parameters.Add(param);
- conn.Open();
- cmd.ExecuteNonQuery();
- } catch (SqlException e){
- Console.Write("SQL Exception: " + e.Message());
- } catch (Exception e) {
- Console.Write("Exception: " e.Message());
- }
示例代碼從本地文件系統(tǒng)插入一個 Word 文檔到數(shù)據(jù)庫中。它與常規(guī)的數(shù)據(jù)庫更新操作類似,然而,F(xiàn)ileStream 和 Bytes 對象用于處理將 Word 文檔插入到數(shù)據(jù)庫中。另外一個變化是使用SqlParameter 對象將 BLOB 插入到數(shù)據(jù)庫字段中。這就允許數(shù)據(jù)可以直接從內(nèi)存寫出到數(shù)據(jù)庫中。
不是所有的數(shù)據(jù)都是相等的,雖然字符串值是開發(fā)人員與數(shù)據(jù)庫交互時最常用的數(shù)據(jù)類型,但是其它數(shù)據(jù)類型也經(jīng)常使用,比如數(shù)字和 BLOB。在編程時,將將這些對象視為二進制流對待。以上介紹C#存儲BLOB對象。
【編輯推薦】