/////////////////////////////////////
// 保存二进制信息到数据库例子
// 作者:winion
// 2001-8-18
// 用于个人学习或者个人作品,请保留这段文字
//////////////////////////////////////
// 用法:
// 建立数据库,建立表(本例表名picc),
// 建立字段,本例SQL Server: ID char(50), pic image
// 然后让 ADOConnection1指向数据库即可
// 作用:
// 从指定目录里查找其子目录,然后在子目录里查找bmp文件,写入数据库
// ID= 指定目录名+子目录序号(1,2,etc)+bmp文件名称(无扩展名)
//////////////////////////////////////
unit main;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Db, ADODB,dbtables, Grids, DBGrids;
type
TForm1 = class(TForm)
ADOConnection1: TADOConnection;
E_Path: TEdit;
B_Save: TButton;
ADO_TPicDB: TADOTable;
Label1: TLabel;
ADO_TPicDBid: TStringField;
ADO_TPicDBpic: TBlobField;
DBGrid1: TDBGrid;
DataSource1: TDataSource;
procedure B_SaveClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
PathName:string;//存放中文路径名称
procedure SavePic(Path:string);
procedure SavePicsToDbFromPath(Dir:string;i:integer);
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.B_SaveClick(Sender: TObject);
begin
//请检查路径的合理性
ADO_TPicDB.Open ;//c:/病历/
if LastDelimiter('/',E_Path.Text)=Length(E_Path.Text) then
begin
PathName:=Copy(E_Path.Text,0,Length(E_Path.Text)-1);
PathName:=Copy(PathName, LastDelimiter('/',PathName)+1,Length(PathName));
end
else begin
PathName:=Copy(E_Path.Text, LastDelimiter('/',E_Path.Text)+1,Length(E_Path.Text));
E_Path.Text:=E_Path.Text+'/';
end;
SavePic(E_Path.Text);
ADO_TPicDB.Close ;
end;
procedure TForm1.SavePic(Path: string);
var
sr: TSearchRec;
i:integer;
begin
i:=0;
if FindFirst(Path+'*.*', faDirectory , sr) = 0 then
begin
if (sr.Name[1]<>'.') and (sr.Attr=faDirectory) then
begin
Inc(i);
SavePicsToDbFromPath(Path+sr.name,i);
end;
while (FindNext(sr) = 0) do
begin
if (sr.Name[1]='.') or (sr.Attr<>faDirectory) then
continue;
inc(i);
SavePicsToDbFromPath(Path+sr.name,i);
end;
FindClose(sr);
end;
end;
procedure TForm1.SavePicsToDbFromPath(Dir: string;i:integer);
var
sr: TSearchRec;
begin
if FindFirst(Dir+'/*.bmp', faAnyFile, sr) = 0 then
begin
if sr.Name[1]<>'.' then
begin
ADO_TPicDB.Append ;
ADO_TPicDB.FieldByName('ID').asstring:= PathName+inttostr(i)+ExtractFileName(sr.Name);
ADO_TPicDBPic.LoadFromFile(Dir+'/'+sr.Name);
ADO_TPicDB.Post;
end;
while FindNext(sr) = 0 do
begin
if sr.Name[1]='.' then
continue;
ADO_TPicDB.Append ;
ADO_TPicDB.FieldByName('ID').asstring:= PathName+inttostr(i)+ExtractFileName(sr.Name);
ADO_TPicDBPic.LoadFromFile(Dir+'/'+sr.Name);
ADO_TPicDB.Post;
end;
FindClose(sr);
end;
end;
end.