Database Reference
In-Depth Information
// Create connection
conn = new SqlConnection(@"server = .\sql2012;integrated security = true;
database = SQL2012Db");
// Open connection
conn.Open();
You call a private class-level method to create a table to hold images.
// Create table
CreatelmageTable();
You call a private class-level method to prepare a command (yes, you finally prepare a command,
since you expect to run it multiple times) to insert images.
// Prepare insert
Preparelnsertlmages();
You then loop through the image files and insert them into the table.
// Loop for Inserting images
for (int i = 1; i <= loader.numberlmageFiles; i++)
{
ExecutelnsertImages(i);
}
Because there could already be a table, you have to take care of dropping the table if it exists and
then creating it. This step is repeated on each run of the application.
When you create the table, a simple one containing the image file name and the image, you use the
VARBINARY(MAX) data type for the imagedata column.
private void CreateImageTable()
{
ExecuteCommand(@"if exists
(select * from
INFORMATION_SCHEMA.TABLES
where TABLE_NAME = 'ImageTable')
drop table ImageTable
create table ImageTable
(
ImageFile nvarchar(20),
ImageData varbinary(max)
)");
}
But when you configure the INSERT command, you use the Image member of the SqlDbType
enumeration, since there is no member for the VARBINARY(MAX) data type. You specify lengths for both
variable-length data types, since you can't prepare a command unless you do.
private void PrepareInsertImages()
{
cmd.CommandText = @"insert into ImageTable
values (@ImageFile, @ImageData)";
 
Search WWH ::




Custom Search