FDQuery append gives error "no such table" - sqlite

In Delphi 10.1 I made a small program to learn about FireDAC and SQlite.
I have FDConnection, FDQuery (with SQL= SELECT * FROM Sætning) and DataSource + DBGrid.
The DBGrid shows the (empty) table Sætning. I want to put data into my table from a listbox containg a CSV.
This is my code: (fdwSætning = an FDQuery)
procedure TMainForm.bCSV_SQLite_SætningClick(Sender: TObject);
var
loop : integer;
nr, lang, tekst : string;
begin
{ Read CSV file into Listbox }
Listbox1.Items.LoadFromFile('GMS_Saetninger.txt');
{ Put the values from the CSV into the fields in each record }
for loop:= 0 to Listbox1.Items.Count-1 do begin
fdqSætning.Edit;
nr:= copy(Listbox1.Items[loop],1,4);
lang:= copy(Listbox1.Items[loop],5,2);
tekst:= copy(Listbox1.Items[loop],8, length(Listbox1.Items[loop]));
fdqSætning.Append;
fdqSætning.FieldByName('SAETNING_ID').AsString:= nr;
fdqSætning.FieldByName('LANGUAGE').AsString:= lang;
fdqSætning.FieldByName('SENTENCE').AsString:= tekst;
fdqSætning.Post;
end;
end;
When I run this code I get the error message
[FireDAC][phys][SQLite]ERROR:no such table: Sætning

That should not happen. Since Delphi 2009, FireDAC fully supports Unicode metadata values, so as does SQLite DBMS. Possible explanation for what you describe is that you've created your table in some external tool (which cannot save Unicode metadata).
So even when I would highly suggest using only ASCII chars for database object names, you can still do something like this with FireDAC since Delphi 2009:
FDConnection.Params.Add('DriverID=SQLite');
FDConnection.Params.Add('Database=C:\MyDatabase.db');
FDQuery.SQL.Text := 'CREATE TABLE ṀÿṪäḅḷë (MɏFɨɇłđ INTEGER)';
FDQuery.ExecSQL;
FDQuery.SQL.Text := 'INSERT INTO ṀÿṪäḅḷë (MɏFɨɇłđ) VALUES (1234)';
FDQuery.ExecSQL;
FDQuery.SQL.Text := 'SELECT MɏFɨɇłđ FROM ṀÿṪäḅḷë';
FDQuery.Open;
Assert(FDQuery.FieldByName('MɏFɨɇłđ').AsInteger = 1234);

Related

Is there a way to INSERT Null value as a parameter using FireDAC?

I want to leave some fields empty (i.e. Null) when I insert values into table. I don't see why would I want to have a DB full of empty strings in fields.
I use Delphi 10, FireDAC and local SQLite DB.
Edit: Provided code is just an example. In my application values are provided by user input and functions, any many of them are optional. If value is empty, I would like to keep it at Null or default value. Creating multiple variants of ExecSQL and nesting If statements isn't an option too - there are too many optional fields (18, to be exact).
Test table:
CREATE TABLE "Clients" (
"Name" TEXT,
"Notes" TEXT
);
This is how I tried it:
var someName,someNote: string;
begin
{...}
someName:='Vasya';
someNote:='';
FDConnection1.ExecSQL('INSERT OR REPLACE INTO Clients(Name,Notes) VALUES (:nameval,:notesval)',
[someName, IfThen(someNote.isEmpty, Null, somenote)]);
This raises an exception:
could not convert variant of type (Null) into type (OleStr)
I've tried to overload it and specify [ftString,ftString] and it didn't help.
Currently I have to do it like this and I hate this messy code:
FDConnection1.ExecSQL('INSERT OR REPLACE INTO Clients(Name,Notes) VALUES ('+
IfThen(someName.isEmpty,'NULL','"'+Sanitize(someName)+'"')+','+
IfThen(someNote.isEmpty,'NULL','"'+Sanitize(someNote)+'"')+');');
Any recommendations?
Edit2: Currently I see an option of creating new row with "INSERT OR REPLACE" and then use multiple UPDATEs in a row for each non-empty value. But this looks direly ineffective. Like this:
FDConnection1.ExecSQL('INSERT OR REPLACE INTO Clients(Name) VALUES (:nameval)',[SomeName]);
id := FDConnection1.ExecSQLScalar('SELECT FROM Clients VALUES id WHERE Name=:nameval',[SomeName]);
if not SomeString.isEmpty then
FDConnection1.ExecSQL('UPDATE Clients SET Notes=:noteval WHERE id=:idval)',[SomeNote,id]);
According to Embarcadero documentation ( here ):
To set the parameter value to Null, specify the parameter data type,
then call the Clear method:
with FDQuery1.ParamByName('name') do begin
DataType := ftString;
Clear;
end;
FDQuery1.ExecSQL;
So, you have to use FDQuery to insert Null values, I suppose. Something like this:
//Assign FDConnection1 to FDQuery1's Connection property
FDQuery1.SQL.Text := 'INSERT OR REPLACE INTO Clients(Name,Notes) VALUES (:nameval,:notesval)';
with FDQuery1.ParamByName('nameval') do
begin
DataType := ftString;
Value := someName;
end;
with FDQuery1.ParamByName('notesval') do
begin
DataType := ftString;
if someNote.IsEmpty then
Clear;
else
Value := someNote;
end;
if not FDConnection1.Connected then
FDConnection.Open;
FDQuery1.ExecSql;
It's not very good idea to execute query as String without parameters because this code is vulnerable to SQL injections.
Some sources tells that it's not enough and you should do something like this:
with FDQuery1.ParamByName('name') do begin
DataType := ftString;
AsString := '';
Clear;
end;
FDQuery1.ExecSQL;
but I can't confirm it. You can try it if main example won't work.

Delphi SqLite Date load to TDateEdit error

I using SQlite database im my Firemonkey Android application and there is no native DateTime type.
I storing date as text type
insert command:
insert into table (value,date_of_change)
values (:val,date('now'));
it works fine, date is correct stored, order by date works fine but if I want load this date into TDate edit
query:
select id,value,date_of_change
from table
where id = :MyID
code:
FDQuery1.Close;
FDQuery1.ParamByName('MyID').Value:= myid;
FDQuery1.OpenOrExecute;
FDQuery1.First;
NumberBox1.Value:=FDQuery1.FieldByName('suma').AsFloat;
DateEdit1.Date:=FDQuery1.FieldByName('date_of_change').AsDateTime;
I get error 2016-10-16 is not valid date and time but in Date edit I can see correct date !
Do anybody knows correct solution of this problem ?
Since you store the date as a string FireDAC fails to parse the format properly. You need to change the way the string value in the database column date_of_change is parsed using the correct date format.
So, instead of doing this:
DateEdit1.Date:=FDQuery1.FieldByName('date_of_change').AsDateTime;
You should do this:
function ParseDateFromDB(const DateStr: String): TDateTime;
var
FormatSettings: TFormatSettings;
begin
FormatSettings.DateSeparator := '-';
FormatSettings.ShortDateFormat := 'YYYY-MM-DD';
Result := StrToDate(DateStr, FormatSettings);
end;
//[...]
DateEdit1.Date := ParseDateFromDB(FDQuery1.FieldByName('date_of_change').AsString);
FireDAC uses its own mapping to SQLite data types and adds the DATE pseudo data type for you. So as there is the SINGLE pseudo data type that you can use for storing value of that number box.
So you can create your table by FireDAC like this:
FDQuery.SQL.Text := 'CREATE TABLE MyTable (DateField DATE, SingleField SINGLE)';
FDQuery.ExecSQL;
Then you can insert data:
FDQuery.SQL.Text := 'INSERT INTO MyTable (DateField, SingleField) VALUES (:DateField, :SingleField)';
FDQuery.ParamByName('DateField').AsDate := DateEdit.Date;
FDQuery.ParamByName('SingleField').AsSingle := NumberBox.Value;
FDQuery.ExecSQL;
And read them for example this way:
FDQuery.SQL.Text := 'SELECT DateField, SingleField FROM MyTable';
FDQuery.Open;
DateEdit.Date := DateOf(FDQuery.FieldByName('DateField').AsDateTime);
NumberBox.Value := FDQuery.FieldByName('SingleField').AsSingle;

How can I create a new SQLite file and table at runtime using FieldDefs?

I'm using Delphi Seattle to create a brand new table in a brand new SQLite file and using only FieldDefs and non-visual code. I can create a table using the ExecSQL ('CREATE TABLE....' ) syntax but not as shown below (I get 'No such table 'MyTable' which is raised when I execute the CreateDataSet call). I'd like some solution that allows me to work with FieldDefs. This code is modelled on the example here. I notice though, that there is note regarding CreateDataSet that it only applies to TFDMemTable. Is there a runtime way of creating an SQLite table without using ExecSQL?
procedure Test;
const
MyDBFile = 'c:\scratch\hope.db';
var
Connection : TFDConnection;
DriverLink : TFDPhysSQLiteDriverLink;
Table : TFDTable;
begin
DeleteFile( MyDBFile );
DriverLink := TFDPhysSQLiteDriverLink.Create( nil );
Connection := TFDConnection.Create( nil );
try
Connection.Params.Values['DriverID'] := 'SQLite';
Connection.Params.Values['Database'] := MyDBFile;
Connection.Connected := True;
Table := TFDTable.Create( nil );
try
Table.TableName := 'MyTable';
Table.Connection := Connection;
Table.FieldDefs.Add( 'one', ftString, 20 );
Table.FieldDefs.Add( 'two', ftString, 20 );
Table.CreateDataSet;
// I would add records here....
finally
Table.Free;
end;
finally
Connection.Free;
DriverLink.Free;
end;
end;
CreateDataSet is usually a local operation for initializing a client-side dataset into an empty state. If TClientDataSet is anything to go by, afaik it cannot be used create a server-side table.
To create an actual server table, I would expect to have to construct the DDL SQL to create the table and then execute it using ExecSQL on the (client-side) dataset, as you have already tried.
update
The following seems to satisfy your requirement to do everything in code, though using a TFDTable component, which doesn't surface FieldDefs, so I've used code-created TFields instead. Tested in D10 Seattle.
procedure TForm3.CreateDatabaseAndTable;
const
DBName = 'd:\delphi\code\sqlite\atest.sqlite';
var
AField : TField;
begin
if FileExists(DBName) then
DeleteFile(DBName);
AField := TLargeIntField.Create(Self);
AField.Name := 'IDField';
AField.FieldName := 'ID';
AField.DataSet := FDTable1;
AField := TWideStringField.Create(Self);
AField.Size := 80;
AField.Name := 'NameField';
AField.FieldName := 'Name';
AField.DataSet := FDTable1;
FDConnection1.Params.Values['database'] := DBName;
FDConnection1.Connected:= True;
FDTable1.TableName := 'MyTable';
FDTable1.CreateTable(False, [tpTable]);
FDTable1.Open();
FDTable1.InsertRecord([1, 'First']);
FDConnection1.Commit;
FDConnection1.Connected:= False;
end;
I expect that someone a bit more familiar than I am could do similar using a TFDMemTable's FieldDefs if it were correctly connected to a server-side component (FDCommand?) via an FDTableAdaptor.
Fwiw, I've used a LargeInt ID field and WideString Name field because trying to use Sqlite with D7 a while back, I had no end of trouble trying to use Integer and string fields.
Btw, you if you know the structure you require in advance of deployment, you might find that you get more predictable/robust results if you simply copy an empty database + table into place, rather than try and create the table in situ. Ymmv, of course.
I would NEVER dream of creating database tables using fielddefs because you wind up having tables without a proper primary key, indexes and referential integrity. The resulting tables are totally "dumbed down".
Whenever you have a "where" clause in a query the database would do a full table scan to find the records matching the query. So your database slows down (and CPU use increases) with size. That's just bad design.
Regards,
Arthur
You can use the app SQLite Expert Professional, create SQLite database.
And using FDConnection connect to the database. And use it.
Method to database SQLite, the same way that MartynA have said.
Begin
FDConnection1.Connected:=false;
FDConnection1.Params.Clear;
FDConnection1.Params.Database:='D:\SQLiteDatabase.db';
FDConnection1.ConnectionDefName:='SQLite_Demo';
FDConnection1.DriverName:='SQLite';
FDConnection1.Connected:=true;
FDTable1.Open;
End;

Why numeric field become TWideStringField after union two datasets in SQLite using TFDQuery

I'm using Delphi 10 Seattle and below is sample codes.
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Datasnap.DBClient,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf,
FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async,
FireDAC.Phys, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef,
FireDAC.Stan.ExprFuncs, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf,
FireDAC.DApt, FireDAC.VCLUI.Wait, FireDAC.Comp.UI, FireDAC.Comp.Client,
FireDAC.Phys.SQLiteVDataSet, FireDAC.Comp.DataSet, Vcl.StdCtrls;
type
TForm1 = class(TForm)
ClientDataSet1: TClientDataSet;
ClientDataSet2: TClientDataSet;
FDConnection1: TFDConnection;
FDQuery1: TFDQuery;
FDLocalSQL1: TFDLocalSQL;
FDPhysSQLiteDriverLink1: TFDPhysSQLiteDriverLink;
FDGUIxWaitCursor1: TFDGUIxWaitCursor;
Button1: TButton;
procedure Button1Click(Sender: TObject);
public
procedure AfterConstruction; override;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.AfterConstruction;
var o: TFDLocalSQLDataSet;
begin
inherited;
ClientDataSet1.FieldDefs.Add('Code', ftString, 20);
ClientDataSet1.FieldDefs.Add('Amount', ftFMTBcd, 2);
ClientDataSet1.FieldDefs.Find('Amount').Precision := 18;
ClientDataSet1.CreateDataSet;
ClientDataSet1.AppendRecord(['A', 10]);
ClientDataSet1.AppendRecord(['B', 20]);
ClientDataSet1.AppendRecord(['C', 30]);
ClientDataSet2.FieldDefs.Add('Code', ftString, 20);
ClientDataSet2.FieldDefs.Add('Amount', ftFMTBcd, 2);
ClientDataSet2.FieldDefs.Find('Amount').Precision := 18;
ClientDataSet2.CreateDataSet;
ClientDataSet2.AppendRecord(['X', 10]);
ClientDataSet2.AppendRecord(['B', 20]);
ClientDataSet2.AppendRecord(['Y', 30]);
o := FDLocalSQL1.DataSets.Add;
o.DataSet := ClientDataSet1;
o := FDLocalSQL1.DataSets.Add;
o.DataSet := ClientDataSet2;
FDLocalSQL1.Active := True;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if FDQuery1.Active then
FDQuery1.Close;
FDQuery1.Open(
'SELECT * FROM ClientDataSet1 ' +
'UNION ' +
'SELECT * FROM ClientDataSet2'
);
ShowMessage(FDQuery1.FindField('Amount').ClassName);
end;
end.
Both instance of TClientDataSet have same fields structure (Code is string field, Amount is FMTBcd field).
Why FDQuery1.FindField('Amount') return TWideStringField?
Your q presupposes that your Amount field was numeric in the first place, but I don't think that's how Sqlite actually works.
Sqlite columns are not strictly typed, and FireDAC is telling you what all Sqlite columns really are, namely WideStrings, even if you declare columns to be of some other type. In Sqlite, defining a column to be of a particular type (f.i. auto-incrementing integer) is more a question of how data in that column behaves rather than how it is stored.
Fwiw, FireDAC in general seems to do a better job of making sense of Sqlite columns and their metadata than DBExpress does, but you still get "funnies" like the one you're asking about.
Apparently (see comment below from an authoritative sorce) if SqlLite supplies a column type name to FireDAC, then FireDAC will try to use the actual data type of the first value which occurs in the column. If it is Null, FireDAC will use ftWideString as the column type.

PL/SQL variable scope in nested blocks

I need to run some SQL blocks to test them, is there an online app where I can insert the code and see what outcome it triggers?
Thanks a lot!
More specific question below:
<<block1>>
DECLARE
var NUMBER;
BEGIN
var := 3;
DBMS_OUTPUT.PUT_LINE(var);
<<block2>>
DECLARE
var NUMBER;
BEGIN
var := 200;
DBMS_OUTPUT.PUT_LINE(block1.var);
END block2;
DBMS_OUTPUT.PUT_LINE(var);
END block1;
Is the output:
3
3
200
or is it:
3
3
3
I read that the variable's value is the value received in the most recent block so is the second answer the good one? I'd love to test these online somewhere if there is a possibility.
Also, is <<block2>> really the correct way to name a block??
Later edit:
I tried this with SQL Fiddle, but I get a "Please build schema" error message:
Thank you very much, Dave! Any idea why this happens?
create table log_table
( message varchar2(200)
)
<<block1>>
DECLARE
var NUMBER;
BEGIN
var := 3;
insert into log_table(message) values (var)
select * from log_table
<<block2>>
DECLARE
var NUMBER;
BEGIN
var := 200;
insert into log_table(message) values (block1.var || ' 2nd')
select * from log_table
END block2;
insert into log_table(message) values (var || ' 3rd')
select * from log_table
END block1;
In answer to your three questions.
You can use SQL Fiddle with Oracle 11g R2: http://www.sqlfiddle.com/#!4. However, this does not allow you to use dbms_output. You will have to insert into / select from tables to see the results of your PL/SQL scripts.
The answer is 3 3 3. Once the inner block is END-ed the variables no longer exist/have scope. You cannot access them any further.
The block naming is correct, however, you aren't required to name blocks, they can be completely anonymous.
EDIT:
So after playing with SQL Fiddle a bit, it seems like it doesn't actually support named blocks (although I have an actual Oracle database to confirm what I said earlier).
You can, however, basically demonstrate the way variable scope works using stored procedures and inner procedures (which are incidentally two very important PL/SQL features).
Before I get to that, I noticed three issues with you code:
You need to terminate the insert statements with a semi-colon.
You need to commit the the transactions after the third insert.
In PL/SQL you can't simply do a select statement and get a result, you need to select into some variable. This would be a simple change, but because we can't use dbms_output to view the variable it doesn't help us. Instead do the inserts, then commit and afterwards select from the table.
In the left hand pane of SQL Fiddle set the query terminator to '//' then paste in the below and 'build schema':
create table log_table
( message varchar2(200)
)
//
create or replace procedure proc1 as
var NUMBER;
procedure proc2 as
var number;
begin
var := 200;
insert into log_table(message) values (proc1.var || ' 2nd');
end;
begin
var := 3;
insert into log_table(message) values (var || ' 1st');
proc2;
insert into log_table(message) values (var || ' 3rd');
commit;
end;
//
begin
proc1;
end;
//
Then in the right hand panel run this SQL:
select * from log_table
You can see that proc2.var has no scope outside of proc2. Furthermore, if you were to explicitly try to utilize proc2.var outside of proc2 you would raise an exception because it is out-of-scope.

Resources