Delphi / ADO : how to get result of Execute()? - delphi

I have declared AdoConnection : TADOConnection; and successfully connected to the default "mysql" database (so, no need to pass that code).
Now, taking baby steps to learn, I would like to AdoConnection.Execute('SHOW DATABASES', cmdText); which seems to work ok, in the sense that it doesn't throw an exception, but I am such a n00b that I don't know how I can examine the result of the command :-/
Halp!

#mawg, the SHOW DATABASES command returns an dataset with one column called 'Database', so you can use the TADOQuery component to read the data.
try this code.
var
AdoQuery : TADOQuery;
begin
AdoQuery:=TADOQuery.Create(nil);
try
AdoQuery.Connection:=AdoConnection;
AdoQuery.SQL.Add('SHOW DATABASES');
AdoQuery.Open;
while not AdoQuery.eof do
begin
Writeln(AdoQuery.FieldByname('DataBase').AsString);
AdoQuery.Next;
end;
finally
AdoQuery.Free;
end;
end;

What you need is to reach the returned _Recordset.
If you don't mind using the Delphi components, you should use TADODataSet or TADOQuery to execute a SQL command which can return any results (or the more low-evel TADOCommands' Execute methods).
If you wanty something realy simple, w/o all the VCL balast, you mignt want to try the TADOWrap class from ExplainThat (MIT licenced).

You must use an TADOQuery connected to TADODataBase. At property SQL you must include the SQl statament to retrive databases in SGDB. In SQL Server you can do this:
SELECT * FROM sysdatabases
In MySQL must exist something similar to retrieve the names.
You can connect this TADOQuery to a TDataSource and a DBGrid to see visual result or use code to explore the result of the query (some similar to this):
ADOQuery1.Open;
while not ADOQuery1.eof do begin
Name := ADOQuery1.FieldByName('DBName').AsString;
ADOQuery1.Next;
end;
Regards

You need TAdoQuery to execute statements, that return results.

If you simply want to populate a grid why dont you use adotable ?
Adotable.open;
Adotable.first;
While NOT adotable.eof do(not sure about not or <>)
Begin
Put values in variant or array;
Adotable.next;
End
Then you can let any UI access the array or variant.
Or populate a dataset.

Related

when packing a dbf table, an error is file is in use

When trying to make a request, it displays an error:
File is in use
How can I solve that program?
procedure TForm1.Button4Click(Sender: TObject);
var data,ffg:string;
begin
data:=formatdatetime('ddmm',(DateTimePicker1.Date));
Adoquery2.SQL.Clear;
adoquery2.SQL.text:='Delete from g_rabn where data=data';// deleting data from g_rabn
adoquery2.ExecSQL;
ShowMessage(SysErrorMessage(GetLastError));
end;
procedure TForm1.Button5Click(Sender: TObject);
begin
Adoquery3.close;
Adoquery3.SQL.Clear;
adoquery3.SQl.text:='pack table g_rabn';// packing tablr g_rabn
adoquery3.Open;
ShowMessage(SysErrorMessage(GetLastError));
end;
end.
I can not delete data from the table, they are marked as deleted but require packaging. How to do it programmatically? He writes that file is in use when packing what to do?
You should execute the statement, not open it as a query. One way to achieve that, is to run it using an TADOCommand, not an TADOQuery, or use the ExecSQL method of the TADOQuery.
Also, all other connections to the DBF must be closed, otherwise you can't get the exclusive access that you need for packing the table.
I found this thread from 2005 on another forum, where somebody made this work with two notable parameters:
Using the provider VFPOLEDB.1
Using just the command pack filename.dbf (without the table keyword).
Lastly, I'm not so sure about the line ShowMessage(SysErrorMessage(GetLastError));. This will show you the last API error, but that's on a low level. You are using the ADO components, so if anything is going wrong, you should expect ADO to throw an exception. For all you know ADO already worked around the issue one way or the other, and the error message you're seeing is not even relevant.
I am surprised that I could not get the solution suggested in Golez Troi's answer
to work, especially as it refers to a newsgroup post from someone who had seemingly managed to pack a dBASE table using ADO; as I said in a comment, if I try to call 'Pack xxxx' to pack a dBASE table via ADO, however I do it, I get
Invalid SQL Statement; DELETE, INSERT, PROCEDURE, SELECT or UPDATE expected
.
I was also surprised to notice something in the MS ODBC dBASE docs that I'd not noticed before, namely that the MS ODBC driver for dBASE files requires the BDE
Note
Accessing dBASE ISAM files through the ODBC Desktop Database Drivers requires installation of the Borland database engine
So, seeing as accessing dBASE files via Ado requires the BDE anyway, there seems to me to be
no point avoiding using the BDE to pack the dBASE table using the standard BDE method, namely to call DbiPackTable. I added a TDatabase and TTable
to my ADO test project, after which I was able to execute this code without any problem
procedure TForm1.Button2Click(Sender: TObject);
begin
try
// Insert code here to close any Ado object (TAdoConnection, TAdoCommand, etc) pointing
// at the dBASE table/file
// Also check that not Ado object pointing at it is open in the IDE
//
// Then ...
Database1.DatabaseName := 'MADBF2';
Database1.Connected := True;
Table1.TableName := 'MATest.Dbf';
Table1.Exclusive := True;
Table1.Open;
// Following uses a call to DbiPackTable to pack the target table
Check(DbiPackTable(Table1.DBHandle, Table1.Handle, nil, nil,True));
finally
Table1.Close;
Database1.Connected := False;
end;
end;
FWIW, while I was writing this answer, I noticed that the BDE.Int file (which gives the declarations but not the implementation of the BDE interface) was on the D7 distribution CD but was apparently not installed by default).

how to copy a ftBlob with firedac arrayDML

I use Delphi Berlin.
I am trying to make a function/procedure to copy data from a FireDac query (connected to a database) to another FireDac query (connected to another database) using ArrayDML. first database is firebird and the other is MSSQL in the first care, but in another case both databases are Firebird.
So far so good and almost all datatype are working correct except ftBlob.
Here is the body of the function:
while not querySource.Eof do begin
paramPosition := -1;
Inc(mIndex);
for i := 0 to querySource.FieldCount - 1 do begin
Inc(paramPosition);
// daca exista o valoare
if querySource.FieldByName(querySource.Fields[i].FieldName).AsVariant <> Null then begin
case querySource.Fields[i].DataType of
ftDateTime, ftDate, ftTime, ftTimeStamp : queryInsert.Params[paramPosition].AsDateTimes[mIndex] := querySource.FieldByName(querySource.Fields[i].FieldName).AsDateTime;
ftFloat, ftCurrency, ftBCD, ftFMTBcd : queryInsert.Params[paramPosition].AsFloats[mIndex] := querySource.FieldByName(querySource.Fields[i].FieldName).AsFloat;
ftSmallint, ftInteger, ftLargeint : queryInsert.Params[paramPosition].AsIntegers[mIndex] := querySource.FieldByName(querySource.Fields[i].FieldName).AsInteger;
ftString : queryInsert.Params[paramPosition].AsStrings[mIndex] := querySource.FieldByName(querySource.Fields[i].FieldName).AsString;
ftBlob, ftMemo, ftGraphic : queryInsert.Params[paramPosition].AsBlobs[mIndex] := querySource.FieldByName(querySource.Fields[i].FieldName).AsVariant;
end;
end;
end;
the blob value is not copy the correct value from the source.
how to use the arrayDML in this case? any workaround?
I won't answer your question but suggest you to use the TFDBatchMove component because you are reinventing wheel here. TFDBatchMove is just for what you want to do, for moving data from one database to another (and not only that).
You simply setup the TFDBatchMoveSQLReader as Reader and Writer, write SQL queries for both and the component will automatically map the fields by matching names. If the queries won't have matching field names, you can fine tune this by the Mappings property. Then you just call Execute.

Getting Delphi 7 to play with SQL Server Compact 3.5

We have an old application that was written in Delphi 7. It is currently connected to an old Oracle Lite database that is being retired. The powers that be have chosen to move the data to a Microsoft SQL Server Compact database instead. After sepending a good amount of time moving everything over to the SQL CE database, I am now tasked with getting the Delphi application to play nice with the new databases.
The people who are supposed to be smarter than I am (my boss), tell me that I should be able to simply modify the connection and everything should be back in order. However, I have been banging my head against my monitor for two days trying to get the ADO connection in the Delphi application to work with our new SQL CE database.
A slightly simplified example of what I'm working with:
The connection is made in a global object with a TADOConnection named "adoConn":
procedure TGlobal.DataModuleCreate(Sender: TObject);
begin
adoConn.ConnectionString := 'Provider=Microsoft.SQLSERVER.CE.OLEDB.3.5;Data Source=path\db.sdf;';
adoConn.Connected := True;
end;
Shortly after this, a procedure is called to populate some messages. In an effort to trouble shoot the application, I've simplified the code to make a simple query and show the results in a message box. The procedure receives a parameter for the SQL string, but I'm ignoring it for now and manually inserting a simple select statement:
procedure Select(const SQL: string);
var
adoQuery : TADOQuery;
begin
adoQuery := TADOQuery.Create(nil);
try
adoQuery.Connection := Global.adoConn;
adoQuery.SQL.Text := 'select * from CLT_MESSAGES';
adoQuery.ExecSQL;
While not adoQuery.Eof do
begin
// Here I just created a MessageDlg to output a couple of fields.
adoQuery.Next;
end;
finally
adoQuery.Free;
end;
end;
Everything compiles just fine, but when I run the application I get the following error:
"Multiple-step operation generated errors. Check each status value."
I've done some additional trouble-shooting and found that the error is happening at adoQuery.ExecSQL. I've tried several different versions of the connection string and a couple different ways of trying to query the data, but it all ends up the same. I either can't connect to the database or I get that stupid "Mutliple-step" error.
I appreciate, in advance, any assistance that can be offered.
Don't use ExecSQL for queries that return recordsets.
Set either the AdoQuery.Active property to True or use AdoQuery.Open to execute a SELECT statement.
UPDATE
After changing your code we see the real error which is DB_E_OBJECTOPEN.
UPDATE2
After digging deeper it seems that this is a known bug in the OLE DB provider and nvarchar fields bigger than 127 characters.
these references seem to confirm this:
SO: SQL Server Compact Edition 3.5 gives "Multiple-step operation generated errors" error for simple query
ref1: http://www.tech-archive.net/Archive/SQL-Server/microsoft.public.sqlserver.ce/2008-07/msg00019.html
ref2: https://forums.embarcadero.com/thread.jspa?messageID=474517
ref3: http://social.msdn.microsoft.com/Forums/en-US/sqlce/thread/48815888-d4ee-42dd-b712-2168639e973c
Changing the cursor type to server side solved the 127 char issue for me :)

Everytime I try to communicate with my database with stored procedures I get this "Cannot perform this operation on a closed dataset"

I'm working on a Delphi project with a MS SQL Server database, I connected the database with ADOConnection, DataSource and ADOProc components from Borland Delphi 7 and I added this code in behind:
procedure TForm1.Button2Click(Sender: TObject);
begin
ADOStoredProc1.ProcedureName := 'sp_Delete_Clen';
ADOStoredProc1.Refresh;
ADOStoredProc1.Parameters.ParamByName('#clenID').Value := Edit6.Text;
ADOStoredProc1.Active := True;
ADOStoredProc1.ExecProc;
end;
The component Edit6 is an editbox that takes the ID of the tuple that should be deleted from the database and ADOStoredProc1 is the stored procedure in the database that takes 1 parametar (the ID you want to delete).
The project runs with no problems, I even got a TADOTable and a DBGrid that load the information from the database, but when I try to delete a tuple from the database using its ID written in the EditBox I get this Error: "Cannot perform this operation on a closed dataset" and the breakpoint of the project is when the application tries to add the value for the 'clenID' parameter.
Where is my mistake and how to fix it?
I think the ADOStoredProc1.Refresh method is not appropriate here. In this case the stored procedure does not return a result set. Could you leave it out? And also the line ADOStoredProc1.Active := True. The connection to the database is open I presume? Could you also check the values of the Parameters collection in the Object Inspector?
I think you want to call ADOStoredProc1.Parameters.Refresh, not ADOStoredProc1.Refresh.
Also, you should only set Active to True if the SQL Server Stored procedure returns a dataset - i.e. the result of a SELECT statement. Setting Active to True is the same as calling Open.
If the stored procedure only returns a result code (RETURN n), then use ExecProc.
In no case should you use both ADOStoredProc1.Active := True; and ADOStoredProc1.ExecProc;
In summary, you probably want something like
procedure TForm1.btnDeleteClick(Sender: TObject);
begin
ADOStoredProc1.ProcedureName := 'sp_Delete_Clen';
ADOStoredProc1.Parameters.Refresh; // gets the parameter list from SQL Server
ADOStoredProc1.Parameters.ParamByName('#clenID').Value := edtID.Text;
ADOStoredProc1.ExecProc;
end;

ADO, Adonis, Update Criteria

On a form, I have a Quantum Grid and some db-aware editcomponents. When appending a new record in the grid, typing some editvalues both in the grid and the separate editcompoennts, I get an error:
EOleException: Row cannot be located for updating. Some values may have been chenged since it was last read
After some googling, I think changing the 'Update Criteria'-property from adCriteriaAllCols to adCriteriaKey may be the right solution. But how, and when, do I do that on a Adonis query?
if your dataset contains an autoincrement field or one or more fields have default values then this may be the problem. After calling Post fields change their value in the db but that may not be detected by your dataset
Although I don't use Adonis, I believe there is a possibility it use the same mechanism TClientDataset (CDS) uses to identify the fields that compose the primary key: the property TField.ProviderFlags.
I believe it could be a good place to start looking.
Actually ADO provides dynamic property to control Query Based Update (QBU) behavior
Most of code is covered in ADOInt.pas, the appropriate event is OnAfterOpen for recordset properties (any TADODataSet), and OnCreate for connection properties (TADOConnection).
I guess ‘Update Criteria’ is not the solution in this case, since it deals with WHERE clause to specify fields to be used for updates.
You may change 'Update Resync' as follows:
//After open a TCustomADODataSet
TCustomADODataSet(DataSet).Properties['Update Resync'].Value :=
adResyncAutoIncrement + adResyncUpdates + adResyncInserts;
if you have join table in your query :
TADOQuery cannot be edit and post data in sql database.
you can create other TADOQuery and select by primary key without any join table and edit and then post data in sql database.
I had a similar problem - Updating a row where all values were the same would result in the error you're getting. I added the flag "Option=2" to the end of my ado connection and this fixed the issue.
This is old. but my situation may happens for someone else. so I post this answer.
This Error happened for me too.
I was using Access database and using some TADOTable on the form.
the relation was master-detail and I connected all of the tables with the IDE Designer together.
my tables were tbl_Floor,tbl_FloorParts,tbl_Seat which tbl_Floor was master of tbl_FloorParts and tbl_FloorParts was master of tbl_Seat.
So for solving this error I did this trick.
procedure Tfrm_Main.UpdateTblFloor(...);
var
FID:Integer;
q:TADOQuery
begin
FID:=tbl_Floor.FieldByName('FID').AsInteger;
tbl_Floor.Close;
q:=TADOQuery.Create(nil);
try
q.Connection:=tbl_Floor.Connection;
q.SQL.Add('Update [Floor]');
q.SQL.Add(...);//Set Fields that needed to be updated
q.SQL.Add('where [FID]='+IntToStr(FID));
q.ExecSQL;
finally
q.free;
end;
tbl_Floor.Open;
tbl_Floor.Locate('FID',FId,[loPartialKey]);
end;
and I added these events for tbl_Floor,tbl_FloorParts
procedure Tfrm_Main.tbl_FloorAfterOpen(DataSet: TDataSet);
begin
tbl_FloorParts.Open;
end;
procedure Tfrm_Main.tbl_FloorBeforeClose(DataSet: TDataSet);
begin
tbl_FloorParts.Close;
end;
procedure Tfrm_Main.tbl_FloorPartsAfterOpen(DataSet: TDataSet);
begin
tbl_Seat.Open;
end;
procedure Tfrm_Main.tbl_FloorPartsBeforeClose(DataSet: TDataSet);
begin
tbl_Seat.Close;
end;

Resources