In this section, we will explore how to work with databases in Delphi/Object Pascal. Databases are essential for storing and managing data in many applications. Delphi provides robust tools and components to interact with various database systems.

Objectives

By the end of this section, you will be able to:

  • Understand the basics of database connectivity in Delphi.
  • Use Delphi components to connect to a database.
  • Perform basic CRUD (Create, Read, Update, Delete) operations.
  • Handle database transactions.
  • Use SQL queries within Delphi applications.

Key Concepts

  1. Database Connectivity

Delphi supports various database systems such as MySQL, SQLite, PostgreSQL, and more. The primary components used for database connectivity in Delphi are:

  • TDataSource: Acts as a bridge between the dataset and data-aware controls.
  • TSQLConnection: Manages the connection to the database.
  • TSQLQuery: Executes SQL queries and retrieves data.
  • TSQLTransaction: Manages database transactions.

  1. Setting Up a Database Connection

To connect to a database, you need to configure the connection parameters such as database name, username, password, and host.

  1. Performing CRUD Operations

CRUD operations are fundamental for interacting with databases. They include:

  • Create: Inserting new records into the database.
  • Read: Retrieving data from the database.
  • Update: Modifying existing records.
  • Delete: Removing records from the database.

  1. Handling Transactions

Transactions ensure data integrity by allowing multiple operations to be executed as a single unit. If any operation fails, the entire transaction can be rolled back.

Practical Example

Step-by-Step Guide to Connecting to a Database

  1. Create a New Delphi Project

    • Open Delphi and create a new VCL Forms Application.
  2. Add Database Components

    • From the Tool Palette, add the following components to your form:
      • TSQLConnection
      • TSQLQuery
      • TDataSource
      • TDBGrid (for displaying data)
  3. Configure TSQLConnection

    • Set the DriverName property to the appropriate database driver (e.g., MySQL, SQLite).
    • Set the Params property with the necessary connection parameters:
      SQLConnection1.Params.Values['Database'] := 'your_database_name';
      SQLConnection1.Params.Values['User_Name'] := 'your_username';
      SQLConnection1.Params.Values['Password'] := 'your_password';
      SQLConnection1.Params.Values['HostName'] := 'your_host';
      
  4. Configure TSQLQuery

    • Set the SQLConnection property to SQLConnection1.
    • Write an SQL query to fetch data:
      SQLQuery1.SQL.Text := 'SELECT * FROM your_table_name';
      
  5. Link TDataSource and TDBGrid

    • Set the DataSet property of TDataSource to SQLQuery1.
    • Set the DataSource property of TDBGrid to DataSource1.
  6. Open the Connection and Fetch Data

    • In the form's OnCreate event, open the connection and execute the query:
      procedure TForm1.FormCreate(Sender: TObject);
      begin
        SQLConnection1.Open;
        SQLQuery1.Open;
      end;
      

Example Code

Here is a complete example of connecting to a MySQL database and displaying data in a grid:

unit Unit1;

interface

uses
  System.SysUtils, System.Classes, Data.DB, Data.SqlExpr, Vcl.Controls, Vcl.Forms, Vcl.DBGrids, Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    SQLConnection1: TSQLConnection;
    SQLQuery1: TSQLQuery;
    DataSource1: TDataSource;
    DBGrid1: TDBGrid;
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
begin
  SQLConnection1.Params.Values['Database'] := 'your_database_name';
  SQLConnection1.Params.Values['User_Name'] := 'your_username';
  SQLConnection1.Params.Values['Password'] := 'your_password';
  SQLConnection1.Params.Values['HostName'] := 'your_host';
  SQLConnection1.DriverName := 'MySQL';
  SQLConnection1.Open;

  SQLQuery1.SQL.Text := 'SELECT * FROM your_table_name';
  SQLQuery1.Open;
end;

end.

Practical Exercises

Exercise 1: Connecting to a Database

  1. Create a new Delphi project.
  2. Add the necessary components (TSQLConnection, TSQLQuery, TDataSource, TDBGrid).
  3. Configure the components to connect to a sample database.
  4. Display the data from a table in the TDBGrid.

Exercise 2: Performing CRUD Operations

  1. Extend the previous project.
  2. Add buttons for Insert, Update, and Delete operations.
  3. Write the necessary SQL queries to perform these operations.
  4. Test the CRUD functionality.

Solution for Exercise 1

procedure TForm1.FormCreate(Sender: TObject);
begin
  SQLConnection1.Params.Values['Database'] := 'sample_db';
  SQLConnection1.Params.Values['User_Name'] := 'root';
  SQLConnection1.Params.Values['Password'] := 'password';
  SQLConnection1.Params.Values['HostName'] := 'localhost';
  SQLConnection1.DriverName := 'MySQL';
  SQLConnection1.Open;

  SQLQuery1.SQL.Text := 'SELECT * FROM sample_table';
  SQLQuery1.Open;
end;

Common Mistakes and Tips

  • Incorrect Connection Parameters: Ensure that the database name, username, password, and host are correct.
  • SQL Syntax Errors: Double-check your SQL queries for syntax errors.
  • Component Linking: Make sure that the TDataSource and TDBGrid are correctly linked to the TSQLQuery.

Conclusion

In this section, we covered the basics of database access in Delphi. You learned how to set up a database connection, perform CRUD operations, and handle transactions. These skills are essential for developing data-driven applications. In the next module, we will delve into object-oriented programming in Delphi.

Delphi/Object Pascal Programming Course

Module 1: Introduction to Delphi/Object Pascal

Module 2: Control Structures and Procedures

Module 3: Working with Data

Module 4: Object-Oriented Programming

Module 5: Advanced Delphi Features

Module 6: GUI Development with VCL and FMX

Module 7: Web and Mobile Development

Module 8: Best Practices and Design Patterns

Module 9: Final Project

© Copyright 2024. All rights reserved