Recent

Author Topic: NullStr to NULL in SQLQuery  (Read 391 times)

BSaidus

  • Hero Member
  • *****
  • Posts: 636
  • lazarus 1.8.4 Win8.1 / cross FreeBSD
NullStr to NULL in SQLQuery
« on: September 22, 2025, 02:03:13 pm »
Hello.

Given this code:


Code: Pascal  [Select][+][-]
  1. // v_int : TLongIntFirld
  2. // v_txtc: TStringField
  3. // v_txtt: TMemoField
  4.  
  5. const
  6.   CSQL = 'INSERT INTO uc_temp (v_int, v_txtc, v_txtt) VALUES (%d, %s, %s);';
  7. var
  8.   LtextSQL: string;
  9.   Lf1: LongInt;
  10.   Lf2, Lf3: String;
  11. begin
  12.  
  13.   if not TryStrToInt(Edit1.Text, Lf1) then
  14.   begin
  15.     // Lf1 = Null;
  16.   end;
  17.      
  18.   Lf2 := Edit2.Text;
  19.   if Trim(Lf2) = '' then
  20.   begin
  21.     // Lf2 = Null;  
  22.   end;
  23.  
  24.   Lf3 := Memo2.Text;
  25.   if Trim(Lf3) = '' then
  26.   begin
  27.     // Lf3 = Null;      
  28.   end;  
  29.  
  30.  
  31.   LtextSQL := Format(CSQL, [Lf1, Lf2, Lf3]);
  32.  
  33.   Memo1.Append(LtextSQL);
  34.  
  35.   Self.ZQuery1.SQL.Clear;
  36.   // ...
  37.  
  38. end;
  39.  

My Question is, How to Convert Empty Value ( for string = '', for Integer = '' ) to Null, in order to when executing
sql statement, the Empty value will be replaced by NULL.

IN my exemple, I use Edit & Memo to get input values, if they are empty then I Format the query with NULL
 
  Ie:

Code: Pascal  [Select][+][-]
  1.  
  2.   LtextSQL := INSERT INTO uc_temp (v_int, v_txtc, v_txtt) VALUES (NULL, NULL, NULL);
  3.  
 


PS: I do not want to construct the query using string concatination.
 
lazarus 1.8.4 Win8.1 / cross FreeBSD
dhukmucmur vernadh!

dseligo

  • Hero Member
  • *****
  • Posts: 1601
Re: NullStr to NULL in SQLQuery
« Reply #1 on: September 22, 2025, 02:12:40 pm »
Use parameters.

You use them like this:
Code: Pascal  [Select][+][-]
  1.   CSQL = 'INSERT INTO uc_temp (v_int, v_txtc, v_txtt) VALUES (:v_int, :v_txtc, :v_txtt)';
  2. ...
  3. ParamByName('v_int').AsInteger := 1;
  4. ParamByName('v_txtc').AsString := 'abc';
  5. ParamByName('txtt').AsString := 'cde';
  6.  

If you want null value, you do it like this:
Code: Pascal  [Select][+][-]
  1. ParamByName('v_int').Clear;

BSaidus

  • Hero Member
  • *****
  • Posts: 636
  • lazarus 1.8.4 Win8.1 / cross FreeBSD
Re: NullStr to NULL in SQLQuery
« Reply #2 on: September 22, 2025, 02:17:16 pm »
Thank you.
I'll do it like that.
lazarus 1.8.4 Win8.1 / cross FreeBSD
dhukmucmur vernadh!

 

TinyPortal © 2005-2018