how to cycle through the table with same data on fields? - delphi

hello i have this code running today but problem is that when there are same data on fields it doesnt cycle but just shows the first data that it filters.
here is the code
ADOTable1.First;
if ADOTable1.Locate('Last', Edit1.Text, []) then
begin
Label1.Caption := ADOTable1.FieldByName('Last').AsString;
Label2.Caption := ADOTable1.FieldByName('First').AsString;
Label3.Caption := ADOTable1.FieldByName('address').AsString;
Next;
end
else
begin
Label1.Caption := '';
Label2.Caption := '';
Label3.Caption := '';
end;

Locate locates the first record that matches the specified criteria in the DataSet.
If a record was found, that record becomes the active/current record.
It cannot be used to locate a "Next" match.
You might want to use a Filter criteria with FindFirst/FindNext e.g.:
DataSet.Filter := 'Last = ''' + Edit1.Text + '''';
if DataSet.FindFirst then
begin
ShowMessage('Found First!');
while DataSet.FindNext do
begin
ShowMessage('Found Next!');
end;
end;
If you want to Filter all records that matches your criteria simply use:
DataSet.Filter := 'Last = ''' + Edit1.Text + '''';
DataSet.Filtered := True; // apply filter for the dataset
Now only those records that meet the filter's conditions are available in the DataSet.
Then iterate the DataSet:
DataSet.First;
while not DataSet.Eof do
begin
// do something with the record
DataSet.Next;
end;

thanks. got this code so far last night
procedure TMain.Button1Click(Sender: TObject);
begin
ADOTable1.First;
while not ADOTable1.EOF do
begin
if (ADOTable1.FieldByName('Last Name').AsString = edit1.Text)
then begin
Label1.Caption := ADOTable1.FieldByName('Last Name').AsString;
Label2.Caption := ADOTable1.FieldByName('First Name').AsString;
Label3.Caption := ADOTable1.FieldByName('MI').AsString;
end;
ShowMessage('click ok for next profile');
ADOTable1.Next;
end;
it maybe same as the code you have given but this code searches for each line on the db grid and thus each line makes me press the ok button once.is it possible to click ok once then the code will search for the next matching data rather than it searching each row?

Related

How to extract the first instance of unique strings

I need to extract a list of unique items from 12 years' worth of consistent computer-generated one-per day text files. The filenames vary only by the included date, so it is easy to generate the required name in code. They consist of a list of all the aircraft movements at my local airport during the given day, in time order. Naturally, the same aircraft come and go many times, and the objective is to loop through the files, pick out the first instance of when each individual aircraft appears (the first visit or FV) copy it to a list and then ignore it from then on. The result should be a list of all the first visits in date order. Should be simple, but... My program is small so I am including the entire implementation code.
procedure TForm1.FormCreate(Sender: TObject);
begin
FileDate := StrToDate('01/01/2007');
FName := 'E:LGW Reports/SBSLGW2007-01-01.txt'; //1st file to be read
FDStr := copy(FName, 21, 10);
TempList := TStringList.Create; //temp holder for file contents
FVCheckList := TStringList.Create; //holds unique identifier (UID)
FVCheckList.Sorted := TRUE;
FVCheckList.Duplicates := dupIgnore;
FVList:= TStringList.Create; //the main output
end;
procedure TForm1.Button1Click(Sender: TObject);
var
i: integer;
begin
Memo1.Lines.Append('Started');
Repeat
TempList.Clear;
TempList.LoadFromFile(FName);
for i := 1 to TempList.Count-1 do
begin
Line := TempList.Strings[i];
//create a //create a Unique identifier (UID) from elements in Line
Serial := Trim(Copy(Line, 22, 9));
MsnPos1 := Pos('[', Line) + 1;
MsnPos2 := Pos(']', Line);
Msn := copy(Line, MsnPos1, (MsnPos2 - MsnPos1));
UID := Serial + '/' + Msn;
//
if (FVCheckList.IndexOf(UID) < 0) then
begin
FVCheckList.Append(UID);
//Add date of file to Line, otherwise it gives no clue when FV was
FVList.Append(FormatDateTime('YYYY-MM-DD', FileDate) + ' ' + Line);
FileDate := IncDay(FileDate, 1);
FName := 'E:LGW Reports/SBSLGW' + FormatDateTime('YYYY-MM-DD', FileDate) + '.txt';
end;
end;
Until FileExists(FName) = FALSE;
FVCheckList.SaveToFile('E:LGW Reports/First Visit Checklist.txt');
FVList.SaveToFile('E:LGW Reports/First Visits.txt');
Memo1.Lines.Append('Finished');
Memo1.Lines.SaveToFile('E:LGW Reports/Files parsed.txt');
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
TempList.Free;
FVCheckList.Free;
FVList.Free;
end;
There are no compiler errors, it runs to completion in seconds and produces the two text files specified, correctly formatted. The big problem is that the lines actually listed in FVList are not always the very first visit of the aircraft, they can be the first, the most recent or somewhere in between. I cannot see any obvious clue as to why the wrong instance is appearing: if my code is right, then something is wrong with the functioning of TStringList FVCheckList. The fault is far more likely to be something I have overlooked, or my understanding of how .dupIgnore works, or maybe my looping isn't working as it should.
I should be very grateful for any practical help. Many thanks in advance.
Repeat
...
Until FileExists(FName) = FALSE;
Should be
While FileExists(FName) = TRUE do
Begin
End;
If the first 2007-01-01 file does not exist, your code will crash on the first LoadFromFile() since you don't check for the file's existence before loading it, unlike with the subsequent files.
Otherwise, I would suggest sticking with repeat but assign FName at the top of each loop iteration instead of initializing it outside the loop and then reassigning at the bottom of each iteration. No need to duplicate efforts.
If you check IndexOf() manually, you don't need to use Sorted or dupIgnore at all. This is what you should be doing in this situation. When dupIgnore ignores a new string, Append() doesn't tell you that the string was ignored. To do that, you would have to check whether the Count was actually increased or not.
Inside the outer loop, the reassignment of FileDate and FName should be outside of the inner for loop,not inside the for loop at all.
Try this instead:
procedure TForm1.FormCreate(Sender: TObject);
begin
FileDate := EncodeDate(2007,1,1);
FDStr := FormatDateTime('YYYY-MM-DD', FileDate);
TempList := TStringList.Create; //temp holder for file contents
FVCheckList := TStringList.Create; //holds unique identifier (UID)
FVList := TStringList.Create; //the main output
end;
procedure TForm1.Button1Click(Sender: TObject);
var
i: integer;
begin
Memo1.Lines.Append('Started');
Repeat
FName := 'E:LGW Reports/SBSLGW' + FormatDateTime('YYYY-MM-DD', FileDate) + '.txt';
if not FileExists(FName) then Break;
Memo1.Lines.Append(FName)
TempList.LoadFromFile(FName);
for i := 1 to TempList.Count-1 do
begin
Line := TempList.Strings[i];
//create a Unique identifier (UID) from elements in Line
Serial := Trim(Copy(Line, 22, 9));
MsnPos1 := Pos('[', Line) + 1;
MsnPos2 := PosEx(']', Line, MsnPos1);
Msn := copy(Line, MsnPos1, (MsnPos2 - MsnPos1));
UID := Serial + '/' + Msn;
if FVCheckList.IndexOf(UID) = -1 then
begin
FVCheckList.Append(UID);
//Add date of file to Line, otherwise it gives no clue when FV was
FVList.Append(FormatDateTime('YYYY-MM-DD', FileDate) + ' ' + Line);
end;
end;
FileDate := IncDay(FileDate, 1);
end;
FVCheckList.SaveToFile('E:LGW Reports/First Visit Checklist.txt');
FVList.SaveToFile('E:LGW Reports/First Visits.txt');
Memo1.Lines.Append('Finished');
Memo1.Lines.SaveToFile('E:LGW Reports/Files parsed.txt');
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
TempList.Free;
FVCheckList.Free;
FVList.Free;
end;

How to add items from an SQL query to a TListView

I want to add items from a query into a TListView using a for loop. But I get an error saying 'Too many actual parameters' from the ListViewShifts.Items.Add() line. What is the correct way of adding to the list from a query?
Qry := TFDQuery.Create(DBConnection);
Qry.Connection := DBConnection;
Qry.SQL.Text := 'SELECT Count(10) FROM Bookings WHERE NurseNo=:nurseID;';
Qry.Params.ParamByName('nurseID').AsInteger := NurseID;
Qry.Active := True;
//Fill the list view with the shifts that have the nurses ID
for Count := 0 to 10 do
begin
ListViewShifts.Items.Add(Qry.Fields[Count].AsString);
end;
You need to consider the following:
If your ListViewShifts variable is TListView, method ListViewShifts.Items.Add doesn't expect parameters. This is the reason for Too many actual parameters error.
SQL statement SELECT Count(10) FROM Bookings WHERE NurseNo=:nurseID; will return result set with only one column.
If you want to get the first 10 rows, then probably your statement should be: SELECT TOP(10) FROM Bookings WHERE NurseNo=:nurseID;
Use First, Eof and Next dataset methods to fetch records from your result set.
Next basic example shows how to add 10 items in your TListView:
procedure TMainForm.btnGet(Sender: TObject);
var
li: TListItem;
begin
Qry := TFDQuery.Create(DBConnection);
Qry.Connection := DBConnection;
Qry.SQL.Text := 'SELECT TOP(10) FROM Bookings WHERE NurseNo=:nurseID;';
Qry.Params.ParamByName('nurseID').AsInteger := NurseID;
Qry.Active := True;
Qry.First;
for Count := 1 to 10 do
begin
Qry.Next;
li := ListViewShifts.Items.Add;
li.Caption := Qry.Fields[0].AsString;
end;
(*
Qry.First;
while not Qry.Eof do begin
li := ListViewShifts.Items.Add;
li.Caption := Qry.Fields[0].AsString;
Qry.Next;
end;
*)
end;
VAR
SY1:INTEGER;
mydata:string;
begin
mydata:='mydatabasename';
qry_tables.Close;
qry_tables.SQL.Clear;
qry_tables.SQL.text:= 'SELECT TABLE_NAME NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = '+QuotedStr(mydata);
qry_tables.Open;
ListViewShifts.Clear;
for SY1 := 1 to qry_tables.RecordCount do
begin
ListViewShifts.Items.Add(qry_tables.FieldByName('NAME').TEXT);
qry_tables.NEXT;
end;
i used mysql

Cannot save some fields and an image

I tried this code to save some fields and an image.
I use MySQL and zzeos for connectinf to the database.
How to fix this code ?
procedure Tfbiodata.btnSaveClick(Sender: TObject);
var
gambar : TMemoryStream;
begin
if (edtnis.Text='') or (edtname.Text='') or (cmbjk.Text='') or (edtempat.Text='') or (edtgl.Text='') or (cmbtingkatan.Text='') then
begin
ShowMessage('Maaf !!! Data Anda Belum Lengkap ....');
exit;
end;
begin
zbiodata2.Open;
zbiodata2.Append;
zbiodata2.FieldByName('NIS').AsString := edtnis.Text;
zbiodata2.FieldByName('Nama_siswa').AsString := edtname.Text;
zbiodata2.FieldByName('Jenis_kelamin').AsString := cmbjk.Text;
zbiodata2.FieldByName('Tempat_lahir').AsString := edtempat.Text;
zbiodata2.FieldByName('Tanggal_lahir').AsString := edtgl.Text;
zbiodata2.FieldByName('Tingkatan').AsString := cmbtingkatan.Text;
zbiodata2.FieldByName('Hasil_indentifkasi').AsString := lblhasil.Caption;
zbiodata2.FieldByName('Metode_pembeaaran').AsString := memo1.Text;
try
convertobmp(openpicture.FileName);
gambar := TMemorystream.Create;
image1.Picture.Graphic.SaveToStream(gambar);
zbiodata2.SQL.Text := 'insert into biodata (gambar) values (:p0)';
zbiodata2.Params[0].LoadFromStream(gambar,ftBlob);
zbiodata2.Post;
zbiodata2.ExecSQL;
except
on E:Exception do
ShowMessage('sorry this a problem .' + #13 + 'Error : ' + E.Message);
end;
end;
end;
When I run this code, I get the error "sorry this is a problem . Error: List index out of bounds(2)"
After calling image1.Picture.Graphic.SaveToStream(gambar), set gambar.Position back to 0 before then calling zbiodata2.Params[0].LoadFromStream(gambar,ftBlob):
image1.Picture.Graphic.SaveToStream(gambar);
gambar.Position := 0; // <-- add this
zbiodata2.Params[0].LoadFromStream(gambar,ftBlob);
With that said, you are using zbiodata2 for two different operations at the same time - editing a new row that is being appended, and executing an SQL statement. Don't do that! Use separate components for each operation.
If the image is being saved into the same row that is being appended, don't bother executing a separate SQL INSERT statement at all. Save the image data directly into the row's gambar TField before then calling zbiodata2.Post():
procedure Tfbiodata.btnSaveClick(Sender: TObject);
var
gambar : TStream;
begin
if (edtnis.Text='') or (edtname.Text='') or (cmbjk.Text='') or (edtempat.Text='') or (edtgl.Text='') or (cmbtingkatan.Text='') then
begin
ShowMessage('Maaf !!! Data Anda Belum Lengkap ....');
Exit;
end;
try
convertobmp(openpicture.FileName);
zbiodata2.Open;
zbiodata2.Append;
try
zbiodata2.FieldByName('NIS').AsString := edtnis.Text;
zbiodata2.FieldByName('Nama_siswa').AsString := edtname.Text;
zbiodata2.FieldByName('Jenis_kelamin').AsString := cmbjk.Text;
zbiodata2.FieldByName('Tempat_lahir').AsString := edtempat.Text;
zbiodata2.FieldByName('Tanggal_lahir').AsString := edtgl.Text;
zbiodata2.FieldByName('Tingkatan').AsString := cmbtingkatan.Text;
zbiodata2.FieldByName('Hasil_indentifkasi').AsString := lblhasil.Caption;
zbiodata2.FieldByName('Metode_pembeaaran').AsString := memo1.Text;
if (image1.Picture.Graphic <> nil) and (not image1.Picture.Graphic.Empty) then
begin
gambar := TMemoryStream.Create;
try
image1.Picture.Graphic.SaveToStream(gambar);
gambar.Position := 0;
(zbiodata2.FieldByName('gambar') as TBlobField).LoadFromStream(gambar);
finally
gambar.Free;
end;
{
Alternatively:
gambar := zbiodata2.CreateBlobStream(zbiodata2.FieldByName('gambar'), bmWrite);
try
image1.Picture.Graphic.SaveToStream(gambar);
finally
gambar.Free;
end;
}
end;
zbiodata2.Post;
except
zbiodata2.Cancel;
raise;
end;
except
on E:Exception do
ShowMessage('sorry this a problem .' + #13 + 'Error : ' + E.Message);
end;
end;
If you are still having problems after that, you need to explain what is actually going wrong, what errors you are seeing, etc.

jSon_encode like function for Delphi which accepts TDataSet

I have been tasked with creating a Indy server in Delphi 2007 which communicates with clients and returns json formatted data from Sql based databases. Someone from our office created a prototype using php. And in the prototype they use the jSon_encode function extensively to return the data from tables. I was wondering if there was a similar Delphi function which could accept a TDataSet parameter and return properly formatted json data.
Anyone know of such function?
Update 12/10/2013 - my modification to #user2748835 answer:
function jsonencode(mString: String): String;
begin
result := StringReplace(mString,'''','\''',[rfReplaceAll,rfIgnoreCase]);
result := StringReplace(mString,'\','\\',[rfReplaceAll,rfIgnoreCase]);
result := StringReplace(result,crlf,'\n',[rfReplaceAll,rfIgnoreCase]);
result := StringReplace(result,'"','\"',[rfReplaceAll,rfIgnoreCase]);
result := StringReplace(result,'/','\/',[rfReplaceAll,rfIgnoreCase]);
result := StringReplace(result,'#9','\t',[rfReplaceAll,rfIgnoreCase]);
end;
function jSon_encode(aDataset:TDataset):string;
function fieldToJSON(thisField:TField):string;
begin
try
result := '"'+thisField.fieldName+'":';
case thisField.DataType of
ftInteger,ftSmallint,ftLargeint:
result := result+inttostr(thisField.AsInteger);
ftDateTime:
result := result+'"'+formatdatetime('YYYY-MM-DD HH:NN:SS',thisField.AsDateTime)+'"';
ftCurrency,
ftFloat:
result := result + floattostr(thisField.AsFloat);
ftString :
result := result + '"'+jsonencode(thisField.AsString)+'"';
else
end; // case
result := result + ',';
except
on e: Exception do begin
appendtolog('problem escaping field '+thisfield.fieldname);
end;
end;
end; // of fieldToJSON
function rowToJSON(ds:TDataset):string;
var
fieldIx : integer;
begin
result := '';
for fieldIx := 0 to ds.fieldcount-1 do
result := result + fieldToJSON(ds.Fields[fieldIx]);
// trim comma after last col
result := '{'+copy(result,1,length(result)-1)+'},';
end; // of rowToJSON
begin
result := '';
with aDataset do
begin
if not bof then first;
while not eof do
begin
result := result + rowToJSON(aDataset);
next;
end;
end;
//strip last comma and add
if length(result)>0 then
result := copy(result,1,length(result)-1);
result := '['+result+']';
end; // of DSToJSON
In a TDataset, you can loop through the Fields collection and construct the json output and then in the loop, check the fieldtype and encode the value accordingly.
Something like:
uses db;
function DSToJSON(aDataset:TDataset):string;
function fieldToJSON(thisField:TField):string;
begin
result := '"'+thisField.fieldName+'":';
case thisField.DataType of
ftInteger,
ftSmallint,
ftCurrency,
ftFloat,
ftLargeInt:
result := result+thisField.value+^n^j;
ftString :
result := noSingleQuotes(thisField.value)+^n^j;
else
end; // case
end; // of fieldToJSON
function rowToJSON(ds:TDataset):string;
var
fieldIx : integer;
begin
for fieldIx := 0 to ds.fieldcount-1 do
result := result + fieldToJSON(ds.Fields[fieldIx]);
// trim comma after last col
result := '{'+copy(result,1,length(result)-1)+'},';
end; // of rowToJSON
begin
result := '';
with aDataset do
begin
if not bof then first;
while not eof do
begin
result := result + rowToJSON(aDataset);
next;
end;
end;
//strip last comma and add
if length(result)>0 then
result := copy(result,1,length(result)-1);
result := '['+result+']';
end; // of DSToJSON
We just added a more complete and faster function, in our Open Source repository.
It is part of our mORMot framework, but can be used as a stand-alone unit, not tied to other features.
See in SynVirtualDataSet.pas:
function DataSetToJSON(Data: TDataSet): RawUTF8
See this commit and the associated forum thread.
You can change every row into object and use serializing http://docwiki.embarcadero.com/RADStudio/XE5/en/Serializing_User_Objects

how to display to a dbgrid my query in this code?

hello is it possible for this code to display to a tdbgrid the search results in a list like style? (e.g. if i searched for john, all the data conataining john on a certain field will be displayed to the tdbgrid)
procedure Tspcb.dccolbtnClick(Sender: TObject);
begin
zdctable.First;
while not zdctable.EOF do
begin
if (zdctable.FieldByName('Collector').AsString = dcedit.Text)
then begin
cn.Caption := zdctable.FieldByName('Client_Name').AsString;
col.Caption := zdctable.FieldByName('Collector').AsString;
pay.Caption := zdctable.FieldByName('Daily_Payment').AsString;
date.Caption := zdctable.FieldByName('Date').AsString;
ddate.Caption := zdctable.FieldByName('Due_Date').AsString;
id.Caption := zdctable.FieldByName('ID').AsString;
la.Caption := zdctable.FieldByName('Loan').AsString;
tc.Caption := zdctable.FieldByName('Total_Collectibles').AsString;
end;
ShowMessage('click ok for next profile');
zdctable.Next;
end;
end;
Just add a datasource, set property dataset to your dataset zdctable, add a DBgrid to your form and set the property datasource to the datasource.
The only piece of code you will need is in the OnchangeEvent of dcedit
procedure TForm3.dceditChange(Sender: TObject);
begin
zdctable.FilterOptions:=[foCaseInsensitive]; // if wished
zdctable.Filtered := Length(dcEdit.Text) > 0;
if zdctable.Filtered then
// zdctable.Filter := 'Collector like ' + QuotedStr('%' + dcEdit.Text + '%')
zdctable.Filter := 'Collector like ' + QuotedStr('*' + dcEdit.Text + '*') // Zeos- Syntax
else zdctable.Filter := '';
end;

Resources