// 从文件中加载二进制图像数据
// LoadImages.cs
// 在C#程序中,二进制数据类型映射为字节数据(byet[]),
// 字符数据类型映射为字符串或者字符数组(char[])
using
System;
using
System.Data;
using
System.Data.SqlClient;
using
System.IO;
namespace
Ch18
{
class
LoadImages
{
// 假设图片文件使用 image1.jpg、image2.jpg..imageX.jpg命名规则存放在当前目录的pic目录下
string
imgPath =
".
\\pic\\
"
;
string
imgPrefix =
"image"
;
int
fileNumber = 3;
string
imgType =
".jpg"
;
int
maxImageSize = 10000;
SqlConnection conn =
null
;
SqlCommand cmd =
null
;
static
void
Main()
{
LoadImages loader =
new
LoadImages();
try
{
loader.OpenConnection();
loader.CreateCommand();
loader.CreateImageTable();
loader.PrepareInsertImages();
int
i;
for
(i = 1; i <= loader.fileNumber; i++)
{
loader.ExecuteInsertImages(i);
}
}
catch
(SqlException ex)
{
Console
.WriteLine(ex.ToString());
}
finally
{
loader.CloseConnection();
Console.WriteLine("博客园首发");
Console
.ReadLine();
}
}
void
OpenConnection()
{
string
strConn =
"server=.\\MSSQL2012;integrated security = true; database=tempdb"
;
conn =
new
SqlConnection(strConn);
conn.Open();
}
void
CloseConnection()
{
conn.Close();
Console
.WriteLine(
"连接关闭"
);
}
void
CreateCommand()
{
cmd =
new
SqlCommand();
cmd.Connection = conn;
}
void
ExecuteCommand(
string
cmdText)
{
int
cmdResult;
cmd.CommandText = cmdText;
Console
.WriteLine(
"执行SQL:"
);
Console
.WriteLine(cmd.CommandText);
cmdResult = cmd.ExecuteNonQuery();
}
void
CreateImageTable()
{
ExecuteCommand(
@"create table imagetable(imagefile nvarchar(20), imagedata varbinary(max))"
);
}
void
PrepareInsertImages()
{
cmd.CommandText =
@"insert into imagetable values(@file,@data)"
;
cmd.Parameters.Add(
"@file"
, SqlDbType.NVarChar, 20);
cmd.Parameters.Add(
"@data"
, SqlDbType.Image, 1000000);
cmd.Prepare();
}
void
ExecuteInsertImages(
int
fileNo)
{
string
strFile =
null
;
byte
[] imgData =
null
;
strFile = imgPrefix + fileNo.ToString() + imgType;
imgData = LoadImageFile(strFile, imgPath, maxImageSize);
cmd.Parameters[
"@file"
].Value = strFile;
cmd.Parameters[
"@data"
].Value = imgData;
ExecuteCommand(cmd.CommandText);
}
byte
[] LoadImageFile(
string
strFile,
string
strPath,
int
iSize)
{
byte
[] imageBytes =
null
;
string
strFullPath = strPath + strFile;
Console
.WriteLine(
"加载文件:"
);
Console
.WriteLine(strFullPath);
FileStream
fs =
new
FileStream
(strFullPath,
FileMode
.Open,
FileAccess
.Read);
BinaryReader
br =
new
BinaryReader
(fs);
imageBytes = br.ReadBytes(iSize);
Console
.WriteLine(
"Imagebytes has length {0} bytes."
, imageBytes.GetLength(0));
return
imageBytes;
}
}
}
------------
执行SQL:
create table imagetable(imagefile nvarchar(20), imagedata varbinary(max))
加载文件:
.\pic\image1.jpg
Imagebytes has length 10000 bytes.
执行SQL:
insert into imagetable values(@file,@data)
加载文件:
.\pic\image2.jpg
Imagebytes has length 10000 bytes.
执行SQL:
insert into imagetable values(@file,@data)
加载文件:
.\pic\image3.jpg
Imagebytes has length 10000 bytes.
执行SQL:
insert into imagetable values(@file,@data)
连接关闭