能否给我一段插入数据库image代码?(50分)

  • 主题发起人 主题发起人 hotdot
  • 开始时间 开始时间
H

hotdot

Unregistered / Unconfirmed
GUEST, unregistred user!
包括产生流,写入流。
注:表名Tab,数据库字段为A,B,C,其中C为image型字段,A为int型,B为varchar型
 
to hotdot:
试试看看一段程序
procedure TForm1.Button2Click(Sender: TObject);
Var
BlobStream:TBlobStream;
JpegImage:TJpegImage;
begin
if OpenPictureDialog1.execute then
image1.picture.LoadFromFile(OpenPictureDialog1.filename);
try
with table1 do
try
edit;
JpegImage:=TJpegImage.Create;
BlobStream:=TBlobStream.Create(TBlobField(FieldByName('p')),bmWrite);
BlobStream.Position:=0;
JpegImage:=TJpegImage(image1.Picture.Graphic);
JpegImage.SaveToStream(BlobStream);
post;
finally
if Not Assigned(BlobStream) then BlobStream.Free;
if Not Assigned(JpegImage) then JpegImage.Free;
end;
except
end;
end;


 
我只写插入Image的代码,这个过程是你Post数据时的过程
procedure ...
var
TempGra : TBitmap;
begin
{存图片}
TempGra := TBitmap.Create;
TempGra.Assign(Image1.Picture.Bitmap); //Image1为获取图片的控件
Tab.Append;
Tab.FieldByName('C').Assign(TempGra);
Tab.FieldByName('A').AsInteger := 1;
..
Tab.Post;
TempGra.Free;
end;
 
用这种方法,好象图象的质量不是很好!
 
据库SQL Server,存放文件的字段类型Image
Create Table MyTable
(
FileName VarChar(20),
FileSource Image
)
存放文件到数据库

var FileName :String;
FileName := ExtractFileName(OpenDialog1.FileName);
with Query do
begin
Close;
Sql.Clear;
Sql.Add('INSERT INTO MyTable VALUES (:FileName,:FileSource)');
ParamByName('FileName').AsString := FileName;
ParamByName('FileSource').LoadFromFile(OpenDialog1.FileName,ftBolob);
ExecSQL;
end;



从数据库中取出文件

var FileName :String;
begin
with Query do begin
Close;
Sql.Clear;
Sql.Add('SELECT * FROM MyTable WHERE FileName = '?'');
Open;
FileName := 'c:/'+FieldByName('FileName').AsString;
(FieldByName('FileSource') AS TBlobField).SaveToFile(FileName);
end;
end;
 
procedure TForm1.btnTargetClick(Sender: TObject);
var
sFileName:String;

function BlobContentToString(const FileName:String):String;
begin
with TFileStream.Create(FileName,fmOpenRead) do
try
SetLength(Result,Size);
Read(Pointer(Result)^,Size);
finally
Free;
end;
end;
begin
if (OpenDialog1.Execute) then
begin
sFileName:=OpenDialog1.FileName;
ADODataSet1.Edit;
ADODataSet1.FieldByName('c').AsString:=
BlobContentToString(sFileName);
ADODataSet1.Post;
end;
end;
 
多人接受答案了。
 

Similar threads

S
回复
0
查看
3K
SUNSTONE的Delphi笔记
S
S
回复
0
查看
2K
SUNSTONE的Delphi笔记
S
D
回复
0
查看
2K
DelphiTeacher的专栏
D
D
回复
0
查看
2K
DelphiTeacher的专栏
D
D
回复
0
查看
1K
DelphiTeacher的专栏
D
后退
顶部