Assume this is our table:
CREATE TABLE dbo.MyPictures
(
Id INT IDENTITY(1,1) NOT NULL,
Picture IMAGE NOT NULL,
CONSTRAINT PK_MyPictures PRIMARY KEY CLUSTERED (Id)
);
This code will insert an image file into the database.
string commandText = "INSERT INTO dbo.MyPictures (Picture) VALUES (@picture);";
byte[] fileBuffer = File.ReadAllBytes("MyPicture.jpg");
using (SqlConnection sqlConnection = new SqlConnection("data source=localhost;initial catalog=Scratch;integrated security=True;"))
using (SqlCommand sqlCommand = new SqlCommand(commandText, sqlConnection))
{
sqlCommand.Parameters.AddWithValue("@picture", fileBuffer);
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
}
Make sure you read the MSDN documentation on using this data type. This is a fixed length field which means if the image is one byte or 100 bytes, both will use the same amount of storage. Also, I wasn't able to confirm this, but rumors have been that Microsoft is planning on dropping support of this data type in favor of the
BINARY
and
VARBINARY
.
ntext, text, and image (Transact-SQL)[
^]