Reinvent your SQL coding with the newly released dbForge AI Assistant
Learn more

Connect to Amazon Redshift from Delphi via UniDAC

Prerequisites
  1. RAD Studio installed on your system
  2. UniDAC from Devart installed
  3. Amazon Redshift connection details: endpoint, port, database name, username, and password
  1. Start your Rad Studio.
  2. Open or create a new project. To do this, navigate File > New > Windows VCL Application – Delphi.
  1. Add the TUniConnection component.
    • 3.1 Navigate to the Component palette and find the UniDAC category.
    • 3.2 Drag and drop the TUniConnection component onto the Form Designer.
  1. Double-click the UniConnection1 label on the form, and in the dialog that opens, configure the following TUniConnection properties:
    • In the Provider dropdown, select Redshift.
    • In the Server field, enter your Redshift cluster endpoint.
    • In the Port field, enter 5439 (default Redshift port).
    • In the Username field, enter your Redshift username.
    • In the Password field, enter your Redshift password.
    • In the Database field, enter the name of your Redshift database.
    • Clear the LoginPrompt checkbox.
  2. Click Connect.

You can use UniDAC components like TUniQuery, TUniTable, or TUniStoredProc to execute SQL queries, access tables, or call stored procedures in your Amazon Redshift warehouse. Below is an example of how to configure a connection to an Amazon Redshift database in your code.

procedure TForm1.ConnectToRedshift;
begin
  UniConnection1.ProviderName := 'Redshift';
  UniConnection1.Server := 'your-redshift-endpoint';
  UniConnection1.Port := 5439;
  UniConnection1.Username := 'your-username';
  UniConnection1.Password := 'your-password';
  UniConnection1.Database := 'your-database';
  UniConnection1.LoginPrompt := False;

  try
    UniConnection1.Connect;
    ShowMessage('Connection successful!');
  except
    on E: Exception do
      ShowMessage('Failed to connect: ' + E.Message);
  end;
end;

This code example can be placed within a method that you call when your form is created or when a specific event is triggered.

Retrieve Amazon Redshift data via UniDAC

UniDAC enables developers to establish a direct connection to Amazon Redshift and access data from it. To retrieve data from an Amazon Redshift database:

  1. Add the TUniQuery and TUniDataSource components.
    To do this, go to the Component palette and locate the UniDAC category. Then, drag and drop the components onto your form.
  2. Add the TRedshiftUniProvider component.
    To do this, drag and drop the TRedshiftUniProvider component onto your form from the UniDACProviders category.
  3. Similarly, add the TButton component from the Standard category and TDBGrid from the Data Controls category.
  1. Double-click the UniQuery1 label in the Form Designer and enter a SQL query to select the data from a database residing on Amazon Redshift.
    For example,
SELECT * FROM employee;
  1. Click OK to save changes and close the dialog.
  1. Click the DBGrid1 label in the Form Designer and set the DataSource property to the UniDataSource1 value in the Object Inspector.
  2. Click the UniDataSource1 label in the Form Designer and set the DataSet property to the UniQuery1 value in the Object Inspector.
  3. Call the Open method in your application to execute the SQL query. To do this, double-click the Button1 label, and in the Code Editor that opens, add the following code:
UniQuery1.Open

The complete procedure code should look like this:

procedure TForm2.Button1Click(Sender: TObject);
begin
  UniQuery1.Open
end;
  1. Click Run.
  2. In the window that opens, click the button to display the result.

Manage fields

Manage fields in the Form Designer

  1. Open the Fields Editor.
    • 1.1 Right-click the UniQuery1 label on your form and select Fields Editor from the shortcut menu.
  2. Add fields to the Fields Editor. In the Fields Editor window, right-click inside the windowand select Add All Fields from the context menu.

Alternatively, you can select New Field to add fields manually.

  1. Manage field properties. After adding fields, you can manage their properties in the Object Inspector. Select each field in the Fields Editor to view and edit its properties, such as DisplayLabel, Visible, ReadOnly, Alignment, etc.

Create Persistent Fields

Adding all fields in the Fields Editor will create persistent fields, which are not created dynamically every time a query is opened or closed. Instead, persistent fields are created as components on the form, and the IDE adds the corresponding form class variables for each field.

After adding persistent fields, you can refer to them directly in your code using their names. For example, if you have a field named employee_id, you can access its value as follows:

EmployeeID := UniQuery1employee_id.AsInteger;

Manage Fields from Code

TUniQuery contains a Fields collection, where each field is represented by a corresponding TField. Fields can be accessed either by their index or by name using the FieldByName method:

UniQuery1.Fields[1]; // Accessing a field by its index
UniQuery1.FieldByName('employee_id'); // Accessing a field by its name

The following example retrieves data and displays it in a TMemo component:

var
 EmployeeID: Integer;
 EmployeeName: String;
begin
 Memo1.Lines.Clear;

 UniQuery1.Open;
 UniQuery1.First;
 
 while not UniQuery1.Eof do
 begin
   EmployeeID := UniQuery1.FieldByName('employee_id').AsInteger;
   EmployeeName := UniQuery1.FieldByName('first_name').AsString + ' ' +
                   UniQuery1.FieldByName('last_name').AsString;
 
   Memo1.Lines.Add(IntToStr(EmployeeID) + ': ' + EmployeeName);
   
   UniQuery1.Next;
 end;
 
 UniQuery1.Close;
end;

The preceding code begins by clearing the lines in Memo1. Then, it opens the query, starts at the first record, and iterates through each record until the end of the file (Eof) is reached. For each record, it retrieves the employee ID and name, formats them, and adds them to the memo. The Next method is used to move the cursor to the next record, and the loop continues until Eof returns true, indicating that there are no more records to process. Finally, the query is closed to free up resources.

For persistent fields, change the code as follows:

var
 EmployeeID: Integer;
 EmployeeName: String;
begin
 Memo1.Lines.Clear;
 
 UniQuery1.Open;
 UniQuery1.First;
 
 while not UniQuery1.Eof do
 begin
   // Access persistent fields directly by their component name
   EmployeeID := UniQuery1employee_id.AsInteger;  // If the field component's name is 'employee_id'
   EmployeeName := UniQuery1first_name.AsString + ' ' +
                   UniQuery1last_name.AsString;  // If the field components' names are 'first_name' and 'last_name'
 
   Memo1.Lines.Add(IntToStr(EmployeeID) + ': ' + EmployeeName);
 
   UniQuery1.Next;
 end;
 
 UniQuery1.Close;
end;

Execute queries

The TUniQuery component can be used not only for selecting data but also for executing any queries supported by the database server. For example, you can update records in the employee table using TUniQuery with an UPDATE statement.

To do this, double-click the TUniQuery label to open the SQL editor and enter the query, for example:

UPDATE employee
SET first_name = 'John', last_name = 'Doe'
WHERE employee_id = 2;
You can execute the query from the editor at design-time by clicking Run.

To execute the query at runtime, call the Execute method of TUniQuery in your code:

UniQuery1.Execute;

Using parameterized queries

You can use parameterized queries to reuse the same query with different parameter values at execution time and prevent SQL injection attacks. For example, your application can get the new values for the first_name and employee_id fields from the user. You can use parameters for this purpose:

UPDATE employee SET first_name = :first_name WHERE employee_id =
:employee_id

Parameters are added using a colon (:) followed by the parameter name. The database server substitutes the parameter names with actual values at runtime.

To define a query with parameters:
  1. In the SQL tab of the TUniQuery editor, enter the query with parameters:
UPDATE employee SET first_name = :first_name WHERE employee_id = 
:employee_id;
  1. Set parameter types.

After defining the query, go to the Parameters tab in the TUniQuery editor. Set the DataType and ParamType for each parameter.

You can access the parameters by index or by name using the Params collection.

UniQuery1.Params[0];
UniQuery1.ParamByName('first_name');

Use the following code to set the parameter values and execute the query:

UniQuery1.ParamByName('first_name').AsString := 'John';
UniQuery1.ParamByName('employee_id').AsInteger := 2;
UniQuery1.Execute;

Each parameter is replaced with a single value in the SQL statement. This approach allows fordynamic query execution based on user input or other runtime conditions.

Using macros

Any part of a statement (such as a table name) can be changed dynamically with macros. Macros are marked with an ampersand (&) followed by the macro name:

SELECT * FROM & macro1

Access macros

Macros are accessed by index or by name from the Macros collection of the TUniQuery component.

UniQuery3.Macros[0];
UniQuery3.MacroByName('MACRO1');

Set macro values

The value of a macro can be set using the Value property of a TMacro. For example:

UniQuery3.MacroByName('MACRO1').Value := 'employee';

Or:

  UniQuery3.MacroByName('MACRO1').Value := 'employee ORDER BY last_name';

Edit data

All the dataset components described above are editable.

To edit data, follow these steps:
  1. Call the Edit method to start editing.
  2. Make changes to the fields.
  3. Call the Postmethod to save the changes to the database or call the Cancel method to discard the changes.
For example:
UniQuery1.Edit;
UniQuery1.FieldByName('HIREDATE').AsDateTime := Now;
UniQuery1.FieldByName('SAL').AsFloat := 1000;
UniQuery1.Post;  // To save changes
// UniQuery1.Cancel;  // To discard changes

Edit data using the Form Designer

Click any cell in the TDBGrid to start editing. The Edit method is called automatically. After making changes, move to another record or press Enter to save the changes. The Post method is called automatically. Press the ESC key to cancel the changes to the current record.

Insert or delete records

Use the TDBNavigator to add new records. The Append or Insert method is called automatically. Enter the values for the new record and move to another record or press Enter to save the changes.
To delete records, you can also use the TDBNavigator. The Delete method is called automatically.

Edit data at runtime

You can use the following code to programmatically edit data at runtime:

procedure TForm1.UpdateEmployee;
begin
  UniQuery1.Edit;
  UniQuery1.FieldByName('first_name').AsString := 'John';
  UniQuery1.FieldByName('salary').AsFloat := 1000;
  UniQuery1.Post;
end;

procedure TForm1.AddEmployee;
begin
  UniQuery1.Append;
  UniQuery1.FieldByName('employee_id').AsInteger := -1;
  UniQuery1.FieldByName('first_name').AsString := 'NEW EMP';
  UniQuery1.FieldByName('hire_date').AsDateTime := Now;
  UniQuery1.FieldByName('salary').AsFloat := 2000;
  UniQuery1.Post;
end;

procedure TForm1.DeleteEmployee;
begin
  UniQuery1.Delete;
end;

Conclusion

UniDAC (Universal Data Access Components) is a robust and flexible toolkit for connecting to a variety of databases, including Amazon Redshift, from a Delphi application. This solution enables developers to benefit from Redshift's high performance and scalability while managing data through a user-friendly and familiar Delphi interface. Devart's UniDAC simplifies complex data manipulations, making it an invaluable resource for developers and database administrators seeking to optimize their database interactions.

Watch how to Install the UniDAC on Windows, Linux, and macOS and Connect to the Database

UniDAC is a specifically designed Delphi Data Access Connector library that allows the development of multi-platform applications in various environments via providing direct access to various Delphi, Lazarus, and C++ Builder databases in 32-bit and 64-bit platforms of Windows, Linux, macOS, iOS, and Android..