开发者

Insert data into database [Delphi]

I'm trying using a TAdoTable component,

  • On form Create I call .Append() and in a button i call .Post()

but it loads the entire table! I don't need it to load anything, just need to insert a row into this table.

I was wondering if there is "good way" of inserting data into database with Ado, i already tried using the a "manual" approach with TAdoCommand but it doesn't seems right to me

  • I generate the INSERT query using Format() and all string fields are escaped with QuotedStr()

Th开发者_运维问答anks in advance!

Arthur.


You can use a TADODataset (or TADOQuery).

The way I do it sometimes is with by setting the CommandText to return 0 records from the table, i.e. SELECT TOP 0 * FROM [table], then use .Append and .Post

But personally, I prefer writing the SQL, such as with a TADOCommand


Use the TADOQuery object if you don't need to display the table's data.

Basically:

  • Use TADOQuery.SQL.Text to set the SQL command
  • Use TADOQuery.ExecSQL method to fire the SQL command


You can also use the TADOCommand component, and have it execute the specific SQL command. If you find yourself performing the same command over and over again (like inserts into a table) then consider using parameters rather than directly changing the SQL for every call. Parameters are easy to use, just place a :PARAMNAME in your sql, then use the parameters object on the ado component your using to set the value. For example:

Assuming the CommandText of the TAdoCommand component contains "INSERT INTO TABLENAME (FIELD1) VALUES (:FIELDVALUE1)"

AdoCommand1.Parameters.ParamByName('FIELDVALUE1').Value := 'TEST'
AdoCommand1.Execute;

When the above sql is executed, then the string "TEST" would be written to FIELD1.


var
  CountVar: Integer;

begin

  TADOConnection1.Execute(ASQLInsertStatement, CountVar, [adExecuteNoRecords]);

end;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜