2012-06-10 52 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因为这个是一款赢取应用程序 –

相关问题