C#
Write the code in the file Program.cs
using Microsoft.Data.SqlClient;
using System.Data.SqlTypes;
using System.IO;
namespace ConsoleApp1
{
internal class Program
{
static void Main(string[] args)
{
string connectString = @"Data Source=localhost;Initial Catalog=MyDatabase1;Integrated Security=True; Trust Server Certificate=True";
// Store image in Database
byte[] imgFile = File.ReadAllBytes(@"D:/file1.png");
AddImageToDatabase(connectString,
"Books", // table
1, // id = 1
imgFile,
"Id",
"Icon"
);
// get image from database
byte[] imageFromDatabase = GetDatabaseImage(connectString,
"Books", // table
1, // id = 1
"Id",
"Icon"
);
// store to file
File.WriteAllBytes(@"D:\file1.png", imageFromDatabase);
}
static byte[] GetDatabaseImage(string connectString, string tableName, int id, string columnNameForId, string columnNameForImage)
{
byte[] imageResult = null;
using (SqlConnection connection = new SqlConnection(connectString))
{
string sqlExpression = $"SELECT {columnNameForImage} FROM {tableName} where {columnNameForId}={id}";
using (SqlCommand cmd = new SqlCommand(sqlExpression, connection))
{
connection.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
SqlBytes sqlBytes = reader.GetSqlBytes(0);
imageResult = new byte[sqlBytes.Length];
sqlBytes.Read(0, imageResult, 0, (int)imageResult.Length);
}
}
connection.Close();
}
}
return imageResult;
}
static void AddImageToDatabase(string connectString, string tableName, int id, byte[] imageBytes, string columnName1, string columnName2)
{
using (SqlConnection connection = new SqlConnection(connectString))
{
string sqlExpression = $"INSERT INTO {tableName} ({columnName1}, {columnName2}) Values (@param1, @param2)";
using (SqlCommand cmd = new SqlCommand(sqlExpression, connection))
{
cmd.Parameters.Add(new SqlParameter("@param1", id));
cmd.Parameters.Add(new SqlParameter("@param2", imageBytes));
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
}
}
}
}
}