將檔案儲存到資料庫中 stream

2021-04-01 02:36:55 字數 2266 閱讀 2182

在程式設計中我們常常會遇到「將檔案儲存到資料庫中」這樣乙個問題,雖然這已不是什麼高難度的問題,但對於一些剛剛開始程式設計的朋友來說可能是有一點困難。其實,方法非常的簡單,只是可能由於這些朋友剛剛開始程式設計不久,一時沒有找到方法而已。

下面介紹一下使用c#來完成此項任務。

首先,介紹一下儲存檔案到資料庫中。將檔案儲存到資料庫中,實際上是將檔案轉換成二進位製流後,將二進位製流儲存到資料庫相應的字段中。在sql server中該字段的資料型別是image,在access中該字段的資料型別是ole物件。

//儲存檔案到sql server資料庫中

fileinfo fi=new fileinfo(filename);

filestream fs=fi.openread();

byte bytes=new byte[fs.length];

fs.read(bytes,0,convert.toint32(fs.length));

sql***mand cm=new sql***mand();

cm.connection=**;

cm.***mandtype=***mandtype.text;

if(**.state==0) **.open();

cm.***mandtext="insert into "+tablename+"("+fieldname+") values(@file)";

sqlparameter spfile=new sqlparameter("@file",sqldbtype.image);

spfile.value=bytes;

cm.parameters.add(spfile);

cm.executenonquery()

//儲存檔案到access資料庫中

fileinfo fi=new fileinfo(filename);

filestream fs=fi.openread();

byte bytes=new byte[fs.length];

fs.read(bytes,0,convert.toint32(fs.length));

oledb***mand cm=new oledb***mand();

cm.connection=**;

cm.***mandtype=***mandtype.text;

if(**.state==0) **.open();

cm.***mandtext="insert into "+tablename+"("+fieldname+") values(@file)";

oledbparameter spfile=new oledbparameter("@file",oledbtype.binary);

spfile.value=bytes;

cm.parameters.add(spfile);

cm.executenonquery()

**中的filename是檔案的完整名稱,tablename是要操作的表名稱,fieldname是要儲存檔案的欄位名稱。

兩段**實際上是一樣的,只是操作的資料庫不同,使用的物件不同而已。

接著,在說說將檔案從資料庫中讀取出來,只介紹從sql server中讀取。

sqldatareader dr=null;

sqlconnection obj**=new sqlconnection();

obj**.connectionstring="data source=(local);user id=sa;password=;initial catalog=test";

sql***mand cm=new sql***mand();

cm.connection=**;

cm.***mandtype=***mandtype.text;

cm.***mandtext="select "+fieldname+" from "+tablename+" where id=1";

dr=cm.executereader();

byte file=null; 

if(dr.read())

filestream fs;

fileinfo fi=new system.io.fileinfo(filename);

fs=fi.openwrite();

fs.write(file,0,file.length);

fs.close();

上面的**是將儲存在資料庫中的檔案讀取出來並儲存文filename指定的檔案中。

在使用上面的**時,別忘了新增system.data.sqlclient和system.io引用。

檔案儲存到資料庫中

最近開發乙個專案,涉及到將檔案儲存到資料庫中,在網上找到了例程,故貼出來,大家共享。下面介紹一下使用c 來完成此項任務。首先,介紹一下儲存檔案到資料庫中。將檔案儲存到資料庫中,實際上是將檔案轉換成二進位製流後,將二進位製流儲存到資料庫相應的字段中。在sql server中該字段的資料型別是image...

檔案儲存到資料庫中

最近專案中遇到新問題,問題描述如下 1 需求 應用後台每天定時讀取本地伺服器上傳的excel 並進行解析。2 背景 因為生產上部署兩台應用伺服器 負載均衡 excel放在nfs共享目錄中,這樣兩台伺服器都能讀取excel。為了防止excel被讀取兩次,所以 中每次讀完會加鎖,乙個應用讀完了,另乙個就...

C 將檔案儲存到資料庫中或者從資料庫中讀取檔案

在程式設計中我們常常會遇到 將檔案儲存到資料庫中 這樣乙個問題,雖然這已不是什麼高難度的問題,但對於一些剛剛開始程式設計的朋友來說可能是有一點困難。其實,方法非常的簡單,只是可能由於這些朋友剛剛開始程式設計不久,一時沒有找到方法而已。下面介紹一下使用c 來完成此項任務。首先,介紹一下儲存檔案到資料庫...