2012-06-10 49 views
1

我正在創建一個應用程序,以使用SQL Server 2008提供的文件流數據類型將Excel文件存儲到數據庫中,現在我一直在搜索互聯網上的最佳實踐方式使用C#中的存儲過程插入它。如何將文件插入到文件流數據類型

到目前爲止,我已經創建了數據庫結構和類,我現在需要做的是實際使用的存儲過程,我被卡住,這裏的代碼段的

OpenFileDialog ofd = new OpenFileDialog(); 
ofd.ShowDialog(); 

if (ofd.CheckFileExists) 
{ 
    ....    
} 

using (SqlConnection conn = new SqlConnection(Murel.Util.DBUtil.CONSTRING)) 
{ 
    try 
    { 
     conn.Open(); 

     using (SqlCommand cmd = new SqlCommand("items_insert", conn)) 
     { 
      cmd.CommandType = CommandType.StoredProcedure; 
      cmd.Parameters.Add(new SqlParameter("@name", "test")); 
      cmd.Parameters.Add(new SqlParameter("@template", HELP)); 

      Guid id = (Guid)cmd.ExecuteScalar(); 

      return true; 
     } 
    } 
    catch (Exception ex) 
    { 
     throw ex; 
    } 
    finally 
    { 
     conn.Close(); 
    } 
    } 

的數據表由一個id這是一個唯一的標識符,名稱和模板是varbinary(max)的,我已經有別的成立,我只需要知道要放什麼東西在

cmd.Parameters.Add(new SqlParameter("@template", HELP)); 

THX,

大流士

+0

閱讀[這裏](http://stackoverflow.com/questions/766926/filestream-in- sql-server-and-c-sharp-for-aspx),這是一個類似的問題。 –

+0

存儲過程是什麼樣的? SQL中的模板定義是什麼? – zmbq

+3

完全不相關,但只是fyi,你應該幾乎總是使用throw而不是throw ex。請參閱http://stackoverflow.com/questions/730250/is-there-a-difference-between-throw-and-throw-ex/730255#730255 –

回答

1

試試這個,這應該工作

byte[] fileContent = new byte[ofd.PostedFile.ContentLength]; 
ofd.PostedFile.InputStream.Read(fileContent, 0,ofd.PostedFile.ContentLength); 
command.Parameters.Add("@FileContent", SqlDbType.VarBinary, -1).Value = fileContent; 

OFD是你的FileUpload控件

+0

我不完全有fileupload因爲這個是一款贏取應用程序 –

相關問題