C#存儲(chǔ)BLOB對(duì)象分析
學(xué)習(xí)C#語(yǔ)言時(shí),經(jīng)常會(huì)遇到C#存儲(chǔ)BLOB對(duì)象問(wèn)題,這里將介紹C#存儲(chǔ)BLOB對(duì)象問(wèn)題的解決方法。
C#存儲(chǔ)BLOB對(duì)象
檢索和C#存儲(chǔ)BLOB對(duì)象是一個(gè)很簡(jiǎn)單的過(guò)程;相反的過(guò)程,在 SQL Server 中C#存儲(chǔ)BLOB對(duì)象,也一樣簡(jiǎn)單。這里我要指出的是,前面的例子中使用了由這個(gè)例子中的代碼存儲(chǔ)到表中的 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)插入一個(gè) Word 文檔到數(shù)據(jù)庫(kù)中。它與常規(guī)的數(shù)據(jù)庫(kù)更新操作類似,然而,F(xiàn)ileStream 和 Bytes 對(duì)象用于處理將 Word 文檔插入到數(shù)據(jù)庫(kù)中。另外一個(gè)變化是使用SqlParameter 對(duì)象將 BLOB 插入到數(shù)據(jù)庫(kù)字段中。這就允許數(shù)據(jù)可以直接從內(nèi)存寫出到數(shù)據(jù)庫(kù)中。
不是所有的數(shù)據(jù)都是相等的,雖然字符串值是開發(fā)人員與數(shù)據(jù)庫(kù)交互時(shí)最常用的數(shù)據(jù)類型,但是其它數(shù)據(jù)類型也經(jīng)常使用,比如數(shù)字和 BLOB。在編程時(shí),將將這些對(duì)象視為二進(jìn)制流對(duì)待。以上介紹C#存儲(chǔ)BLOB對(duì)象。
【編輯推薦】