怎样向SQL Server插入带有Image字段的记录
向SQL Server插入记录相信大家都会做,但是如果表中带有Image字段就不好弄了,这里有一个例子,非常安全,同时也向大家展示动态生成控件的技巧(对高手来说班门弄斧了)
procedure Button1Click(Sender:TObject);
var
Query : TQuery;
StringStream : TStringStream;
begin
StringStream := TStringStream.Create ('');
Memo.Lines.SaveToStream (StringStream); //在这里创建一个字符流
StringStream.Position := 0;
Query := TQuery.Create(self); //在这里创建一个临时的Query
Query.DatabaseName := Database.DatabaseName;
with Query.SQL do
begin
Clear;
Append ('INSERT INTO TEST');
Append ('(ID,CONTENT)'); //CONTENT是一个Image字段
Append ('VALUES (:ID, :CONTENT)');
end;
with Query do
begin
ParamByName ('ID').asInteger := StrToIntDef (edtID.Text,0);
ParamByName ('CONTENT').asBlob := StringStream.DataString; //就在这里赋值
end;
StringStream.Free; //用完了马上Free掉
Database.StartTransaction; //开始事务控制
try
Query.ExecSQL; //开始插入记录
Database.Commit; //提交事务
except
Query.Free; //如果出错首先将Query Free掉
Database.RollBack; //回退事务
raise; //重新引发异常,以通知用户
end;
Query.free;
end;