Show sqlite query results in a TEdit - Firemonkey Mobile application? - sqlite

I have an sqlite database and i want to execute a select query and show the result in the TEdit. How can i do it?
query := 'SELECT username FROM users'; //The query returns only one row
FDQuery1.ExecSQL;
FDQuery1.Open();
Edit1.Text := ??

Edit1.Text := FDQuery1.Fields[0].AsString;
Please note that ExecSQL executes an SQL statement that does not return data, while Open executes a SELECT query.
So you are executing the query twice.

In your case, because you only have 1 column I would use:
Edit1.Text := FDQuery1.Fields[0].AsString;
But if you have mulitple column you select I would use:
Edit1.Text := FDQuery1.fieldbyname(<ColumnName>).AsString;

ExecSQL haven't return value
Examp:
FDQuery1.sql.add:= 'SELECT username FROM users';
FDQuery1.Open();
Edit1.Text := FieldByName('username').AsString;

Related

How to get the ID of the last record inserted in SQLite with Delphi 10?

Delphi 10 with Firemonkey and SQLite: After running the code below I want to get the ID of the last record inserted into an SQLite table. How do I get the last ID?
NOTE: The ID field of Table 1 is autoincrement.
var myQr: TFDQuery;
begin
myQr := TFDQuery.Create(Self);
with myQr do begin
SQL.Add('Insert into table1 values (:_id, :_name, :_dthr)');
Params.ParamByName('_id').ParamType := TParamType.ptInput;
Params.ParamByName('_id').DataType := TFieldType.ftInteger;
Params.ParamByName('_id').Value := null;
ParamByName('_name').AsString := 'name test';
ParamByName('_dthr').AsDateTime := Now;
ExecSQL;
end;
// How to get last ID? <<<<<<<<<<<<<=================
myQr.DisposeOf;
You could query last_insert_rowid if your ID column is declared as INTEGER PRIMARY KEY. In such case the column becomes alias for the ROWID. If that is your case, you can query it natively e.g. this way:
uses
FireDAC.Phys.SQLiteWrapper;
function GetLastInsertRowID(Connection: TFDConnection): Int64;
begin
Result := Int64((TObject(Connection.CliObj) as TSQLiteDatabase).LastInsertRowid);
end;
Or in common way by calling GetLastAutoGenValue method:
function GetLastInsertRowID(Connection: TFDConnection): Int64;
begin
Result := Int64(Connection.GetLastAutoGenValue(''));
end;

SQL database data into an array

I currently have a program which connects to a database and displays the data on a DBGrid, however I need to extract this data so I can use it in another algorithm.
When I use the command: select scores from quiz
It shows the values on the screen. (23,55,64)
How do I get these values into an array so that
[0]=23
[1]=55
[2]=64
Thanks in advance.
Best to use TList (which is an array wrapper object). Below is an excerpt from some code that I use. TSomeRect is a record to store the field data of each row in.
function CreateQuery(pConnection: Tsqlconnection; pTransaction: TSQLTransaction): TSQLQuery;
begin
result := TSQLQuery.Create(nil);
result.Database := pConnection;
result.Transaction := pTransaction
end;
var
connect: TSQLite3Connection;
SQLQuery1: TSQLQuery;
transact: TSQLTransaction;
Query : TSQLQuery;
lst :TList<TSomeRect>;
rec :TSomeRect;
begin
lst :=TList<TSomeRect>.create;
connect:=TSQLite3Connection.create(nil);
connect.LoginPrompt := False;
connect.DatabaseName := 'c:\path\to\database.sqlite';
connect.KeepConnection := False;
transact:=TSQLTransaction.create(nil);
transact.action:=caNone;
transact.database:=connect;
connect.Transaction:=transact;
Query := CreateQuery(Connect, Transact);
Query.SQL.Text := 'select * from table';
Connect.Open;
Query.Open;
while not Query.Eof do
begin
rec.field1:= Query.FieldByName('field1').AsInteger;
rec.field2:= Query.FieldByName('field2').Asstring;
lst.add(rec);
Query.Next;
end;
Query.Close;
Connect.Close;
Query.Free;
Transact.Free;
Connect.Free;

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 to insert a string into sQlite.sdb (FireDac)?

I am trying to insert some text into a sqlite database.
I am using FireDac connection and FireDac Query(FDQuery1) to connect to the sqLite database.
Here is code.
FDQuery1.SQL.Text := 'select * from Invoice where Name = :Name';
FDQuery1.ParamByName('Name').AsString := '123';
FDQuery1.Open;
LinkListControlToField1.BindLink.FillList
I seems there is a new record inserted in the database but all fields are null.
What could be the problem ?
Now i am using
NEW_NAME:='dfddf';
SQL :='INSERT INTO INVOICE (Name) VALUES (:NEW_NAME)';
fdquery1.Close;
fdquery1.SQL.Text:= SQL;
FdQuery1.Open();
FDQuery1.Insert;
//Fdquery1.ParamByName('New_Name').AsString := NEW_NAME;
//fdquery1.SQL.Text:='INSERT INTO INVOICE (Name) VALUES (:NEW_NAME)';
fdquery1.FieldByName('Name').AsString := quotedstr(NEW_NAME);
//fdquery1.ExecSQL();
fdquery1.Post;
I am getting eerror message.
FireDac, Phys,Sqlite - 308 Can not open/define command, wiich does not return result sets. Hint use Execute? ExecSql metnod for non Select commands.
As you can see from the commented code I am trying the ExecSql but same error.
While SELECT sql statements cannot insert data into a table, records can be inserted/appended through TDataset descendents that are connected to a table via a SELECT sql statement.
For example:
FDQuery1.SQL.Text := 'select * from Invoice';
FDQuery1.Open;
NEW_NAME:='dfddf';
FDQuery1.Append; // or FDQuery1.Insert;
FDQuery1.FieldByName('Name').AsString := NEW_NAME;
// set other column values as needed
FDQuery1.Post;
If you prefer to use an INSERT:
FDQuery1.SQL.Text := 'INSERT INTO INVOICE (Name) VALUES (:NEW_NAME)';
NEW_NAME := 'dfddf';
FDQuery1.ParamByName('NEW_NAME').AsString := NEW_NAME;
// you will have to define parameters for each column
FDQuery1.ExecSQL;
Replace FDQuery1.Open to FDQuery1.ExecSQL;
But you statment "Select *..." dont Insert any record in database...

Using as in the TSQLQuery

I've been evaluating Delphi XE4 (compiling against win32, but final platform will be iOS) and I need to create SQLite database (no problem with that) and make some queries. This is one query I'd like to use:
select id as _id, name, note as description from notes
And this is my code:
q := TSQLQuery.Create(nil);
try
q.SQLConnection := MainForm.sqlite1;
q.SQL.Text := sql;
q.Open;
finally
q.Free;
end;
The problem is that query returns original field names (id, name, note), not the one I used (_id, name, description).
q.Fields[0].FieldName = 'id' //it should be _id
q.Fields[2].FieldName = 'note' //it should be description
That makes all sorts of problems. Using
count(*) as myfield
returns
q.Fields[0].FieldName = Column0 //it should be myfield
that is not acceptable.
Anybody had same problems?
In order to get the proper alias names of the fields, you must add the ColumnMetaDataSupported param to the Params property of the TSQLConnectioncomponent with the False value.

Resources