1

I am currently working on a Bed and Breakfast management system. I want to create a Microsoft access field in Delphi using code. The field name I want to create is rooms, I want the data type to be text and I want the size to be 6. I found some code on a stack overflow post but not everything. I dont know what to put in the brackets.

//Adds the field to the ms access database

Adotable2.fielddefs.add()
3
  • The documentation is there to help you know what to put in the brackets. Just note that Add is provided for backward compatibility. The recommended way to add new field definitions to the Items property array is using the AddFieldDef method. . So... see also Creating and Deleting Tables. Commented Apr 26, 2020 at 13:03
  • Does the Access table already contain a "Rooms" field, or are you looking to add it to the table? Commented Apr 26, 2020 at 14:44
  • @MartynA no I do not have a "Rooms" field in the database yet. I'm looking to create it in Delphi Commented Apr 26, 2020 at 16:43

1 Answer 1

4

It is quite simple to add a field to an Access table, provided no app has the table open at the time. However, using FieldDefs.Add is not the way to do it, because it does something else which isn't relevant to this task.

Assuming your Delphi form (or datamodule) has an AdoTable1 set up to access the table you want to alter, and that the table's name in the Access database is 'Hotels', this will add the Rooms column to it:

procedure TForm1.Button1Click(Sender: TObject);
begin
  if AdoTable1.Active then //  close the Hotels table if AdoTable1 accesses it
    AdoTable1.Close;
  try
    AdoConnection1.Connected := True;
    AdoConnection1.Execute('alter table Hotels add column rooms text(6)');
  finally
    AdoTable1.Open;
  end;
end;

Note: My AdoConnection1 is set up to access the database using the 'Microsoft Office 16 Access Database Engine OLE DB Provider'.

Btw, if you use "persistent fields" in your AdoTable (the list of fields you get if you right-click on it and select 'Fields Editor ...' from the pop-up menu, you will need to add the Rooms field to it. If you don't use persistent fields, you don't need to worry about this.

The FieldDefs.Add you mentioned is for adding a field in your Delphi app to e.g. AdoTable1 if, for some reason, it did not already include it, for example if you added the field to the table using the MS Access app.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.