Estoy tratando de guardar archivos de Excel en la base de datos, no quiero usar filestream ya que es necesario tener un servidor para eso.
Entonces, ¿cómo inserto / actualizo / selecciono en la tabla que tiene una columna de tipo varbinary(max)
?
Si desea hacerlo directamente en ADO.NET, y sus archivos de Excel no son demasiado grandes para que puedan caber en la memoria a la vez, puede usar estos dos métodos:
// 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(); } }
Para recuperar la hoja de Excel y almacenarla en un archivo, use este método:
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); }
Por supuesto, puede adaptar esto a sus necesidades, también podría hacer muchas otras cosas, dependiendo de lo que realmente quiera hacer (no está muy claro en su pregunta).
Depende de la tecnología de acceso a datos que esté utilizando. Por ejemplo, si usa Entity Framework, solo puede guardar una matriz de bytes en la base de datos usando objetos.