2

I want to store images into a database using SQL commands, I know other ways using TBlobField.LoadFromFile etc, but we make our own sql commands to update the database that's why I need to do this.

How should I go about doing this?

4 Answers 4

5

I've never tried this (and away from desk at the moment), but would parameters work? eg:

Query.Sql.Clear;
Query.Sql.Add('update myTable set myField = :blobVal where myId = :idVal');
Query.ParamByName('idVal').AsInteger := SomeId;
Query.ParamByName('blobVal').LoadFromFile(....
//or
Query.ParamByName('blobVal').LoadFromStream(....
Query.ExecSql;

This allows you to use SQL (rather than the .Edit, etc methods) and still insert blob data

Sign up to request clarification or add additional context in comments.

Comments

0

If I understand correctly, you have some sort of SQL-generation system instead of using datasets, and you want to know how to generate the SQL to do an INSERT or UPDATE to a Blob field correctly.

What you'll need is a way to serialize your image to a string. For example:

function ImageToString(image: TImage): string;
var
  stream: TStringStream;
begin
  stream := TStringStream.Create;
  try
    image.SaveToStream(stream);
    result := image.DataString;
  finally
    stream.Free;
  end;
end;

Once that's ready, put a token in your SQL, something like set IMAGE_FIELD = $IMAGE$, and then use StringReplace to replace the $IMAGE$ token with the string representation of your image.

Or you could use parameters, like Graza suggested, if the system you're working with supports them.

2 Comments

I tried doing what you suggested but the sql command doesn't like the string made for the Image, it's got some quotes and other characters in it. I have tried the same thing using a file and that works fine.
Oh yeah, you've gotta use QuotedStr() inside the StringReplace. Or run it through a routine that converts the whole blob string to hex and sticks "0x" on the front. (This may not work on all DBMSes. Not certain.)
0

Try this:

Query.Sql.Clear;
Query.Sql.Add('update myTable set myField = :blobVal where myId = :idVal');
Query.ParamByName('idVal').AsInteger := SomeId;
Query.Params.CreateParam(ftBlob,'blobVal',ptInput).LoadFromFile('c:\path.png',ftGraphic);
Query.ExecSql;

Comments

0
jpg := TJPEGImage.Create;
jpg.Assign(Image1.Picture.Graphic);
strm := TMemoryStream.Create;
strm.Position:= 0;
jpg.SaveToStream(strm);
IBSQL1.Close;
IBSQL1.SQL.Clear;
IBSQL1.SQL.Add('INSERT INTO ENTRY(FORMNUM, JPG) VALUES(');
IBSQL1.SQL.Add(    quotedstr(edtFormNum.Text));
IBSQL1.SQL.Add(',  :JPG');
IBSQL1.SQL.Add(')');
IBSQL1.Params.ByName('JPG').LoadFromStream(strm);
IBSQL1.ExecQuery;
strm.Free;
jpg.Free;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.