![](/img/trans.png)
[英]How to Store and Retrieve a varbinary(max) Column in SQL Server
[英]How do I insert/retrieve Excel files to varbinary(max) column in SQL Server 2008?
我正在嘗試將Excel文件保存到數據庫中,我不想使用文件流,因為它需要具有服務器。
那么,如何在具有varbinary(max)
類型的列的表中插入/更新/選擇呢?
如果要在直接的ADO.NET中執行此操作,並且您的Excel文件不太大,因此它們可以一次放入內存,則可以使用以下兩種方法:
// store Excel sheet (or any file for that matter) into a SQL Server table
public void StoreExcelToDatabase(string excelFileName)
{
// if file doesn't exist --> terminate (you might want to show a message box or something)
if (!File.Exists(excelFileName))
{
return;
}
// get all the bytes of the file into memory
byte[] excelContents = File.ReadAllBytes(excelFileName);
// define SQL statement to use
string insertStmt = "INSERT INTO dbo.YourTable(FileName, BinaryContent) VALUES(@FileName, @BinaryContent)";
// set up connection and command to do INSERT
using (SqlConnection connection = new SqlConnection("your-connection-string-here"))
using (SqlCommand cmdInsert = new SqlCommand(insertStmt, connection))
{
cmdInsert.Parameters.Add("@FileName", SqlDbType.VarChar, 500).Value = excelFileName;
cmdInsert.Parameters.Add("@BinaryContent", SqlDbType.VarBinary, int.MaxValue).Value = excelContents;
// open connection, execute SQL statement, close connection again
connection.Open();
cmdInsert.ExecuteNonQuery();
connection.Close();
}
}
要檢索Excel工作表並將其存儲在文件中,請使用以下方法:
public void RetrieveExcelFromDatabase(int ID, string excelFileName)
{
byte[] excelContents;
string selectStmt = "SELECT BinaryContent FROM dbo.YourTableHere WHERE ID = @ID";
using (SqlConnection connection = new SqlConnection("your-connection-string-here"))
using (SqlCommand cmdSelect = new SqlCommand(selectStmt, connection))
{
cmdSelect.Parameters.Add("@ID", SqlDbType.Int).Value = ID;
connection.Open();
excelContents = (byte[])cmdSelect.ExecuteScalar();
connection.Close();
}
File.WriteAllBytes(excelFileName, excelContents);
}
當然,您可以根據自己的需求進行調整-您也可以做很多其他事情-取決於您真正想做的事情(問題不太清楚)。
這取決於您使用的數據訪問技術。 例如,如果您使用實體框架,則可以使用對象將字節數組保存到數據庫中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.