I'm trying to load a Image control from a image blob saved previously in a sql database.I have testd so many ways and i can't make it work. The image blob is saved as:
qry.SQL.Text := 'update tbl set pic = :blobVal where id = :idVal';
qry.Parameters.ParamByName('blobVal').LoadFromFile('c:\sample.jpg', ftBlob);
qry.Parameters.ParamByName('idVal').Value := 1;
any suggestion?
There a a lot of treads here about loading images to as database, but I did not find one with update or insert parameters.
You might simply assign a graphic object to your parameter.
If you want to store different graphic types you should add a column
keeping the Information which kind of graphic should be stored (e.g. jpeg,bmp,png).
to be able to create the needed TGraphic class descendant if you want to retrieve the picture from the database.
uses jpeg, pngimage;
type
TitTYPES=(itJPG,itPNG,itBMP);
procedure TDEMO.Button1Click(Sender: TObject);
var
jp:TJpegimage;
g:TGraphic;
begin
jp:=TJpegimage.Create;
try
ads.Close;
jp.LoadFromFile('C:\Bilder1\PIC.jpg');
ads.SQL.Text := 'Insert into IMGBlob (ID,Blob,typ) Values (:ID,:BLOB,:typ)';
ads.Parameters[0].Value := 1;
ads.Parameters[1].Assign(jp);
ads.Parameters[2].Value := itJPG;
ads.ExecSQL;
ads.SQL.Text := 'Select * from IMGBlob where ID=:ID';
ads.Parameters[0].Value := 1;
ads.Open;
try
case TitTYPES(ads.FieldByName('typ').AsInteger) of
itJPG: g:=TJpegimage.Create;
itPNG: g:=TPNGImage.Create;
itBMP: g:=TBitmap.Create;
end;
g.Assign(ads.FieldByName('Blob'));
Image1.Picture.Assign(g);
finally
g.Free;
end;
finally
jp.Free;
end;
end;
To load a BLOB field into an image, you need to use TDataSet.CreateBlobStream.
var
Stream: TStream;
JPG: TJpegImage;
begin
JPG := TJpegImage.Create;
try
Stream := Qry.CreateBlobStream(Qry.FieldByName('BLOBVAL'), bmRead);
try
JPG.LoadFromStream(Stream);
finally
Stream.Free; // edited
end;
finally
JPG.Free;
end;
end;
To store the image back, you'll need to do the reverse:
var
Stream: TBlobStream;
Jpg: TJpegImage;
begin
Jpg := TJpegImage.Create;
try
Jpg.Assign(Image1.Picture.Graphic);
// Assign other query parameters here
Stream := Qry.CreateBlobStream(Qry.FieldByName('BLOBVAL'), bmWrite);
try
Jpg.SaveToStream(Stream);
Qry.ExecSQL;
finally
Stream.Free;
end;
finally
Jpg.Free;
end;
end;
TDBImage is only designed to work with bitmaps (when the field is ftGraphic), so it won't work with JPEG images directly. The easiest thing to do is to load the blob as a JPEG, and assign it to a standard TImage.Picture.Graphic in an event handler for the dataset (such as it's AfterScroll event).
save to db:
var
ms:tmemorystream;
Begin
ms:=tmemorystream.create;
ms.position:=0;
image1.picture.bitmap.savetostream(ms);
ms.position:=0;
with yourfield as tblobfield do
loadfromstream(ms);
freeandnil(ms);
end;
Load from db:
var
ms:tmemorystream;
Begin
ms:=tmemorystream.create;
ms.position:=0;
with yourfield as tblobfield do
savetostream(ms);
ms.position:=0;
image1.picture.bitmap.loadfromstream(ms);
freeandnil(ms);
end;
It does not work with all graphic types like PNG etc.
This one does work on PNG as well:
var mBitmap : TGraphic;
var mStream : TStream;
var mClass : TGraphicClass;
begin
mStream := Query.CreateBlobStream(Query.FieldByName('yourBlobfield'), bmRead);
mClass := GetGraphicClassForFileExtension(mStream.ReadAnsiString);
mBitmap := mClass.Create;
mBitmap.LoadFromStream(mStream);
Image4.Picture.Assign(mBitmap);
end;
Related
I am trying to load an image as blob into a ListView.
Table:
CREATE TABLE [Pictures](
[PicId] INT,
[UsersImage] BLOB);
Code:
procedure LoadFromBlob;
var
BlobStream: TStream;
begin
Form4.FDConnection1.Connected := True;
try
Form4.FDQuery1.Active := True;
Form4.viewimgquery.Active := True;
Form4.FDQuery1.Open;
Form4.viewimgquery.Open;
Form4.viewimgquery.First;
while (not Form4.viewimgquery.EOF) do
begin
// access a stream from a blob like this
BlobStream := Form4.viewimgquery.CreateBlobStream
(Form4.viewimgquery.FieldByName('UsersImage'), TBlobStreamMode.bmRead);
// access a string from a field like this
if (Form4.viewimgquery.FieldByName('PicId')
.AsInteger = Form4.FDQuery1.FieldByName('ID').AsInteger) then
begin
// load your blob stream data into a control
Form4.viewimage.Bitmap.LoadFromStream(BlobStream);
Form4.ListView1.items.Add();
BlobStream.Free;
Form4.viewimgquery.Next;
end;
end;
except
on e: Exception do
begin
// ShowMessage(e.Message);
end;
end;
Form4.FDConnection1.Connected := False;
end;
Query:
SELECT *
FROM PICTURES
WHERE PICID = :PicId
If I change it to select * from pictures and set query to active at design time I see all images loaded into the ListView so my live bindings are set up correctly. But when I call the procedure nothing is loaded into the ListView.
I want to store images in a database using sql but cant seem to get it to work:
qry.SQL.Clear;
qry.Sql.Add('update tbl set pic = :blobVal where id = :idVal');
qry.Parameters.ParamByName('idVal')._?:=1;
.Parameters has no .asinteger like .Param has but .Param isn't compatible with a TADOquery - to workaround I tried:
a_TParameter:=qry.Parameters.CreateParameter('blobval',ftBlob,pdinput,SizeOf(TBlobField),Null);
a_TParam.Assign(a_TParameter);
a_TParam.asblob:=a_Tblob;
qry.ExecSql;
This also doesnt work:
qry.SQL.Clear;
qry.Sql.Add('update tbl set pic = :blobVal where id = 1')
qry.Parameters.ParamByName('blobVal').LoadFromStream(img as a_TFileStream,ftGraphic);//ftblob
//or
qry.Parameters.ParamByName('blobVal').LoadFromFile('c:\sample.jpg',ftgrafic);//ftblob
qry.ExecSql;
Should be something like:
qry.Parameters.Clear;
qry.Parameters.AddParameter.Name := 'blobVal';
qry.Parameters.ParamByName('blobVal').LoadFromFile('c:\sample.jpg', ftBlob);
// or load from stream:
// qry.Parameters.ParamByName('blobVal').LoadFromStream(MyStream, ftBlob);
qry.Parameters.AddParameter.Name := 'idVal';
qry.Parameters.ParamByName('idVal').Value := 1;
qry.SQL.Text := 'update tbl set pic = :blobVal where id = :idVal';
qry.ExecSQL;
To read the BLOB back from the DB:
qry.SQL.Text := 'select id, pic from tbl where id = 1';
qry.Open;
TBlobField(qry.FieldByName('pic')).SaveToFile('c:\sample_2.jpg');
I'm using Lazarus, not Delphi, but I guess its usually the same syntax. If so, here's a slight improvement on kobiks suggestion:
Parameters are added automatically if the SQL.Text is assigned before trying to assign values to the parameters. Like this:
qry.Parameters.Clear;
qry.SQL.Text := 'update tbl set pic = :blobVal where id = :idVal';
qry.Parameters.ParamByName('blobVal').LoadFromFile('c:\sample.jpg', ftBlob);
qry.Parameters.ParamByName('idVal').Value := 1;
qry.ExecSQL;
I wrote this as an answer to this q,
Delphi save packed record as blob in a sql database
which is currently flagged as a duplicate, possibly incorrectly because the technique
used by the OP as described in comments appears to be correct. So, the cause of the problem may lie elsewhere.
If the Duplicate flag gets removed, I'll re-post this answer there.
The following code works fine for me against a Sql Server table defined as shown below.
The data from Rec1 is saved into the table and correctly read back into Rec2.
(* MS Sql Server DDL
CREATE TABLE [blobs] (
[id] [int] NOT NULL ,
[blob] [image] NULL ,
CONSTRAINT [PK_blobs] PRIMARY KEY CLUSTERED
(
[id]
) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
*)
TForm1 = class(TForm)
ADOConnection1: TADOConnection;
qBlobInsert: TADOQuery;
qBlobRead: TADOQuery;
Button1: TButton;
procedure Button1Click(Sender: TObject);
[...]
type
TMyRecord = packed record
FontName: string[30];
FontSize: word;
FontColor: integer;
FontStyle: word;
Attachement: string[255];
URL: string[255];
end;
const
scInsert = 'insert into blobs(id, blob) values(:id, :blob)';
scSelect = 'select * from blobs where id = %d';
procedure TForm1.Button1Click(Sender: TObject);
begin
TestInsert;
end;
procedure TForm1.TestInsert;
var
Rec1,
Rec2 : TMyRecord;
MS : TMemoryStream;
begin
FillChar(Rec1, SizeOf(Rec1), #0);
FillChar(Rec2, SizeOf(Rec2), #0);
Rec1.FontName := 'AName';
Rec1.URL := 'AUrl';
MS := TMemoryStream.Create;
try
// Save Rec1 using an INSERT statement
MS.Write(Rec1, SizeOf(Rec1));
MS.Seek(0, soFromBeginning);
qBlobInsert.Parameters[0].Value := 1;
qBlobInsert.Parameters[1].LoadFromStream(MS, ftBlob);
qBlobInsert.SQL.Text := scInsert;
qBlobInsert.ExecSQL;
// Read saved data back into Rec2
qBlobRead.SQL.Text := Format(scSelect, [1]);
qBlobRead.Open;
MS.Clear;
TBlobField(qBlobRead.FieldByName('blob')).SaveToStream(MS);
MS.Seek(0, soFromBeginning);
MS.Read(Rec2, MS.Size - 1);
Caption := Rec2.FontName + ':' + Rec2.URL;
finally
MS.Free;
end;
end;
Extract from DFM
object qBlobInsert: TADOQuery
Connection = ADOConnection1
Parameters = <
item
Name = 'id'
DataType = ftInteger
Value = Null
end
item
Name = 'blob'
DataType = ftBlob
Value = Null
end>
Left = 56
Top = 32
end
I am on Oracle 11g. I am trying to do a Find and Replace functionality on a CLOB field (using REPLACE).
Now the data in my CLOB has CRLFs in them, the replace works just fine until I want to find a string that contains CRLFs. Perhaps this would be best explained by example:
So say the text in my field is:
----------------------------------
Hi there this is some text
that has CRLFS in it.
Some other text that
is there also.
Have a nice day
Now what I want to do is replace all occurrences of this INCLUDING the CRLFs:
Search Text
--------------------------------------------------------------------------------
Some other text that
is there also.
With this text INCLUING the CRLFs:
Replace Text
------------------------------------
Some other text that
has some new text that is there also.
So That could come out to be:
----------------------------------
Hi there this is some text
that has CRLFS in it.
Some other text that
has some new text that is there also.
Have a nice day
Now I am doing this in a stored procedure and the Search Text and Replace Text come in as variables, but When I try and say where like % || ReplaceText || '%' it returns 0 rows.
Does anyone have an idea how to do this?
Here is my stored procedure (iOldResponsibilities is the Search Text, iNewResponsibilities is the replace text:
PROCEDURE FindReplaceResponsibilities (
iOldResponsibilities IN JP_JOB_FAMILIES.RESPONSIBILITIES%TYPE,
iNewResponsibilities IN JP_JOB_FAMILIES.RESPONSIBILITIES%TYPE,
oNumRowsUpdated OUT INTEGER
)
IS
BEGIN
oNumRowsUpdated := 0;
SAVEPOINT sp_jf_findrepresp;
-- If there is no old text to search for then,
-- append the new text to the end of every row.
-- Else replace all occurrences of the old text with the new text
IF iOldResponsibilities IS NULL THEN
UPDATE JP_JOB_FAMILIES
SET RESPONSIBILITIES = RESPONSIBILITIES || iNewResponsibilities;
oNumRowsUpdated := SQL%ROWCOUNT;
ELSE
UPDATE JP_JOB_FAMILIES
SET RESPONSIBILITIES = REPLACE(RESPONSIBILITIES, iOldResponsibilities, iNewResponsibilities)
WHERE RESPONSIBILITIES like '%' || iOldResponsibilities || '%';
-- I have also tried this:
--WHERE dbms_lob.instr(RESPONSIBILITIES, TO_CLOB(iOldResponsibilities)) > 0; -- This is a LIKE for CLOBS
oNumRowsUpdated := SQL%ROWCOUNT;
END IF;
RETURN;
EXCEPTION
WHEN OTHERS THEN
BEGIN
oNumRowsUpdated := -1;
ROLLBACK TO sp_jf_findrepresp;
dbms_output.put_line('error: ' || sqlerrm);
RETURN;
END;
END FindReplaceResponsibilities;
The Text is coming from an asp.net application (c#) as String values:
public int FindReplaceJobFamilyResponsibilities(String oldResponsibilities, String newResponsibilities, IDbTransaction transaction = null)
{
using (IDbCommand cmd = this._dataHelper.GetStoredProcedure(_connectionString,
"JP_JOBFAM_PKG.FindReplaceResponsibilities", true))
{
_dataHelper.SetParameterValue(cmd, "iOldResponsibilities", oldResponsibilities);
_dataHelper.SetParameterValue(cmd, "iNewResponsibilities", newResponsibilities);
DataHelperBase.VerifyParameters(cmd.Parameters, false);
base.SetExecuteConnection(cmd, transaction);
_dataHelper.ExecuteNonQuery(cmd);
return Convert.ToInt32(_dataHelper.GetParameterValue(cmd, "oNumRowsUpdated"));
}
}
Turns out to be a case of bad data. The data in my Test DB was corrupted and only had LFs instead of CRLFs.
GIGO :-)
Thanks for all your help
Oh and by the way In my code example I went with the INSTR function instead of the like function. If the user entered a % in the text to search through that might have messed up the like statement. (Can't filter those out because % might be a valid character in my data)
Here is the Final Code:
PROCEDURE FindReplaceResponsibilities (
iOldResponsibilities IN JP_JOB_FAMILIES.RESPONSIBILITIES%TYPE,
iNewResponsibilities IN JP_JOB_FAMILIES.RESPONSIBILITIES%TYPE,
oNumRowsUpdated OUT INTEGER
)
IS
BEGIN
oNumRowsUpdated := 0;
SAVEPOINT sp_jf_findrepresp;
-- If there is no old text to search for then,
-- append the new text to the end of every row.
-- Else replace all occurrences of the old text with the new text
IF iOldResponsibilities IS NULL THEN
UPDATE JP_JOB_FAMILIES
SET RESPONSIBILITIES = RESPONSIBILITIES || iNewResponsibilities;
oNumRowsUpdated := SQL%ROWCOUNT;
ELSE
UPDATE JP_JOB_FAMILIES
SET RESPONSIBILITIES = REPLACE(RESPONSIBILITIES, iOldResponsibilities, iNewResponsibilities)
WHERE dbms_lob.instr(RESPONSIBILITIES, iOldResponsibilities) > 0;
oNumRowsUpdated := SQL%ROWCOUNT;
END IF;
RETURN;
EXCEPTION
WHEN OTHERS THEN
BEGIN
oNumRowsUpdated := -1;
ROLLBACK TO sp_jf_findrepresp;
dbms_output.put_line('error: ' || sqlerrm);
RETURN;
END;
END FindReplaceResponsibilities;
The code from my application was fine:
public int FindReplaceJobFamilyResponsibilities(String oldResponsibilities, String newResponsibilities, IDbTransaction transaction = null)
{
using (IDbCommand cmd = this._dataHelper.GetStoredProcedure(_connectionString,
"JP_JOBFAM_PKG.FindReplaceResponsibilities", true))
{
_dataHelper.SetParameterValue(cmd, "iOldResponsibilities", oldResponsibilities);
_dataHelper.SetParameterValue(cmd, "iNewResponsibilities", newResponsibilities);
DataHelperBase.VerifyParameters(cmd.Parameters, false);
base.SetExecuteConnection(cmd, transaction);
_dataHelper.ExecuteNonQuery(cmd);
return Convert.ToInt32(_dataHelper.GetParameterValue(cmd, "oNumRowsUpdated"));
}
}
Using TADOCommand to update a record.
using TADOCommand to insert a new record.
Name of table is Board
Using MS Access database
I get an error
Syntax error in UPDATE/INSERT INTO statement
I can connect and retrieve data just fine. Just never added or updated data before.
My database columns looks like this
ID (auto number)
SN (text)
CardType (text)
Desc (memo)
dbDate (date)
Tech (text)
Code looks like this:
procedure TForm2.BSaveClick(Sender: TObject);
const
sqlStringNew = 'INSERT INTO Board (SN,CardType,Desc,dbDate,Tech) VALUES (:aSN,:aCardType,:aDesc,:aDate,:aTech);';
sqlStringUpdate = 'UPDATE Board SET SN=:aSN, CardType=:aCardType, Desc=:aDesc, dbDate=:aDate, Tech=:aTech WHERE ID = :aID;';
var
ADOCommand : TAdoCommand;
begin
ADOCommand := TADOCommand.Create(nil);
// updating a board
if NewBoard = false then
begin
try
ADOCommand.Connection := adoConnection1;
ADOCommand.Parameters.Clear;
ADOCommand.Commandtext := sqlStringUpdate;
ADOCommand.ParamCheck := false;
ADOCommand.Parameters.ParamByName('aSN').Value := ESerialNumber.Text;
ADOCommand.Parameters.ParamByName('aCardType').Value := ECardType.Text;
ADOCommand.Parameters.ParamByName('aDesc').Value := MDescription.Text;
ADOCommand.Parameters.ParamByName('aDate').Value := strtodate(EDate.Text);
ADOCommand.Parameters.ParamByName('aTech').Value := ETech.Text;
ADOCommand.Parameters.ParamByName('aID').Value := UpdateID;
ADOCommand.Execute;
finally
ADOCommand.Free;
end;
Showmessage('Update Complete');
end;
//if a new board
if NewBoard = True then
Begin
try
ADOCommand.Connection := adoConnection1;
ADOCommand.Parameters.Clear;
ADOCommand.Commandtext := sqlStringNew;
ADOCommand.ParamCheck := false;
ADOCommand.Parameters.ParamByName('aSN').Value := ESerialNumber.Text;
ADOCommand.Parameters.ParamByName('aCardType').Value := ECardType.Text;
ADOCommand.Parameters.ParamByName('aDesc').Value := MDescription.Text;
ADOCommand.Parameters.ParamByName('aDate').Value := strtodate(EDate.Text);
ADOCommand.Parameters.ParamByName('aTech').Value := ETech.Text;
ADOCommand.Execute;
finally
ADOCommand.Free;
end;
NewBoard := false;
BSave.Enabled := false;
NoEdit;
Showmessage('New Record Added');
End;
end;
It is advisable not to use SQL keywords for table and field names. DATE is a function in many SQL dialects. If you choose to use a reserved word/function name for a table/field name, you have to escape it in SQL statement: [Date] for SQL Server and MS Access, "Date" - for Oracle.
Can anyone help me to protect a selection group or component.
For examples
If ('Readme.txt').selected or ('compact').selected = True then
begin "Password wizard page";
else
result := true;
end;
Something like that to this working script :P
function CheckPassword(Password: String): Boolean;
begin
result := false;
if (Password='component') or (Password='type') then
result := true;
end;
I'm not sure I completely understood your question, but maybe this helps. Here are a few functions you only need to add to the [code] section of the Components.iss sample, and one of the components ("help") can only be installed when the user enters the correct password.
Since you need the password later in the installation, and not always, you can not use the standard setup password page. You will instead create your own page and insert it after the components selection page:
[Code]
var
PasswordPage: TInputQueryWizardPage;
procedure InitializeWizard();
begin
PasswordPage := CreateInputQueryPage(wpSelectComponents,
'Your caption goes here',
'Your description goes here',
'Your subcaption goes here');
PasswordPage.Add(SetupMessage(msgPasswordEditLabel), True);
end;
Note that this uses the translated password caption, you may need to make the other three strings translatable as well.
Next you will need to hide that page if the user has not selected the component for installation:
function ShouldSkipPage(PageID: Integer): Boolean;
begin
Result := False;
if PageID = PasswordPage.ID then begin
// show password page only if help file is selected for installation
Result := not IsComponentSelected('help');
end;
end;
Finally you need to check the password, and prevent the user from going to the next page if the password is wrong:
function NextButtonClick(CurPageID: Integer): Boolean;
begin
Result := True;
if CurPageID = PasswordPage.ID then begin
// stay on this page if password is wrong
if PasswordPage.Edits[0].Text <> 'my-secret-password' then begin
MsgBox(SetupMessage(msgIncorrectPassword), mbError, MB_OK);
Result := False;
end;
end;
end;