Reputation: 43
How is a programmer able to add an image to a SQL server database from a wcf service?
This is the code that implements adding the image from the wcf service:
public static void StoreImageIntoDB(string imagePath)
{
string connectionString = "server=XXXX.XXXX.XXXX.XXXX;uid=sa;password=XXXXXX;database=XXXXXX;";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
string sql = "insert into ImageTable values (@img)";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
FileStream fs = new FileStream(imagePath, FileMode.Open, FileAccess.ReadWrite);
byte[] imageBytes = new byte[fs.Length];
fs.Read(imageBytes, 0, Convert.ToInt32(fs.Length));
fs.Dispose();
cmd.Parameters.Add("@img", SqlDbType.Image).Value = imageBytes;
cmd.ExecuteNonQuery();
}
}
}
public static void RetrieveImageFromDB()
{
string connectionString = "server=XXXX.XXXX.XXXX.XXXX;uid=sa;password=XXXXXX;database=XXXXXX;";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
string sql = "select * from ImageTable";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet set = new DataSet();
adapter.Fill(set);
foreach (DataRow row in set.Tables[0].Rows)
{
byte[] imageBytes = row[1] as byte[];
MemoryStream ms = new MemoryStream(imageBytes);
Image image = Image.FromStream(ms);
image.Save(string.Format(@"D:\{0}.jpg", row[0].ToString()));//Save the image to disk
image.Dispose();
ms.Dispose();
}
}
}
}
Now I am in need of knowing how to implement this in the SQL server. I'm assuming it's a query, but do not know where to begin.
Upvotes: 0
Views: 872
Reputation: 983
I object on several levels - the table needs a primary key and other control data. This design is seriously flawed, but the answer to the question as asked given the code that we have been told works as intended, would be
CREATE TABLE ImageTable ( ImageBinary VARBINARY(MAX) )
I suggest you read up on TSQL DDL (ref https://msdn.microsoft.com/en-us/library/ff848799.aspx) and perhaps get a book on database design.
Much better would be something more like
CREATE TABLE ImageTable ( ImageID INT IDENTITY PRIMARY KEY
, ImageBinary VARBINARY(MAX)
, Added DATETIME DEFAULT GETDATE()
)
which would change your insert to
string sql = "insert into dbo.ImageTable( ImageBinary ) values (@img)";
and your retrieval to
string sql = "select ImageBinary from dbo.ImageTable";
But now you have a primary key if you wanted one image at a time or the ability to remove an image, and you could limit the retrieval to a date range or go in ascending or descending order.
Upvotes: 2