Showing posts with label Firebird. Show all posts
Showing posts with label Firebird. Show all posts

Friday, 29 November 2013

How to use TpFIBDataSet, TpFIBQuery and TpFIBTransaction FIBPlus components to connect with Firebird / Interebase database in Delphi XE4?

How to use TpFIBDataSet, TpFIBQuery and TpFIBTransaction FIBPlus components to connect with Firebird / Interebase database in Delphi XE4?

Following is the basic article on Firebird / Interbase database connectivity in Delphi XE4 using FIBPlus database components like TpFIBDataSet, TpFIBQuery and TpFIBTransaction. I will explain all these FIBPlus database components in detail. I have written a small article on TpFIBDatabase before this article. Please go through that before reading this one. Read FIBPlus TpFIBDatabase...

FIBPlus TpFIBQuery Component

An application works with a database by issuing SQL instructions. They are used to get and modify data\metadata. FIBPlus has a special TpFIBQuery component responsible for SQL operator execution. This robust, light and powerful component can perform any actions with the database. 

TpFIBQuery is very easy-to-use: just set the TpFIBDatabase component, fill in the SQL property and call any ExecQuery method (ExecQueryWP, ExecQueryWPS). 

NOTE: The tpFIBQuery is not a TDataset descendant, so it does not act in exactly the same way or exhibit the same methods / properties as you would expect to find in a dataset. 

The example below will show how to create TpFIBQuery dynamically at run-time and thus get data about clients.

 var sql: TpFIBQuery;
 sql := TpFIBQuery.Create(nil);
 with sql do
 try
 Database := db;
 Transaction := db.DefaultTransaction;
 SQL.Text := 'select first_name, last_name from customer';
 ExecQuery;
 while not Eof do begin
 Memo1.Lines.Add(
 FldByName['FIRST_NAME'].AsString+' '+
 FldByName['LASTST_NAME'].AsString);
 Next; end;
 sql.Close;
 finally
 sql.Free;
 end;

FIBPlus TpFIBDataSet component

The TpFIBDataSet component is responsible for work with datasets. It is based on the TpFIBQuery component and helps to cache selection results. TpFIBDataSet is a TDataSet descendant so it supports all TDataSet properties, events and methods.

TpFIBDataSet enables you to select, insert, update and delete data. All these operations are executed by TpFIBQuery components in TpFIBDataSet. 

To select data you set the SelectSQL property. It’s similar to setting the SQL property of the QSelect component (TpFIBQuery type). Define the InsertSQL.Text property to insert data, UpdateSQL.Text to update, DeleteSQL.Text to delete and RefreshSQL.Text to refresh the data. 

Here is a demo database employee.gdb (or .fdb for Firebird) to show how to write Select SQL and get a list of all employees. I will write all queries in InsertSQL, UpdateSQL, etc.

with pFIBDataSet1 do begin
 if Active then Close;

 SelectSQL.Text := 'select CUST_NO, CUSTOMER, CONTACT_FIRST, CONTACT_LAST from CUSTOMER';

 InsertSQL.Text := 'insert into CUSTOMER(CUST_NO, CUSTOMER, CONTACT_FIRST,                                           CONTACT_LAST )' + 
                              ' values (:CUST_NO, :CUSTOMER, :CONTACT_FIRST, :CONTACT_LAST)';

 UpdateSQL.Text := 'update CUSTOMER set CUSTOMER = :CUSTOMER, '+
                   'CONTACT_FIRST = :CONTACT_FIRST, CONTACT_LAST = :CONTACT_LAST '+
                   'where CUST_NO = :CUST_NO';

 DeleteSQL.Text := 'delete from CUSTOMER where CUST_NO = :CUST_NO';

 RefreshSQL.Text := 'select CUST_NO, CUSTOMER, CONTACT_FIRST, CONTACT_LAST '                                       + 'from CUSTOMER where CUST_NO = :CUST_NO';

 Open;
end;

To open TpFIBDataSet either execute Open/OpenWP methods or set the Active property to True. To close TpFIBDataSet call the Close method

FIBPlus TpFIBTransaction component

A transaction is an operation of database transfer from one consistent state to another. All operations with the dataset (data/metadata changes) are done in the context of a transaction. To understand special FIBPlus features completely you need to know about InterBase / FIBPlus transactions. 

All the changes done in the transaction can be either committed (in case there are no errors) by Commit or rolled back (Rollback). Besides these basic methods TpFIBTransaction has their context saving analogues: CommitRetaining and RollbackRetaining, i.e. on the client side, these will not close a TpFibQuery or TpFibDataset.

To start the transaction you should call the StartTransaction method or set the Active property to True. To commit the transaction call Commit/CommitRetaing, to roll it back - Rollback/RollbackRetaining. 

TpFIBQuery and TpFIBDataSet components have some properties which help to control transactions automatically. In particular they are: the TpFIBDataSet.AutoCommit property; the poStartTransaction parameter in TpFIBDataSet.Options; qoStartTransaction and qoCommitTransaction in TpFIBQuery.Options.

TpFIBTransaction has three basic transaction types: 
tpbDefault, 
tpbReadCommited, 
tpbRepeatableRead. 

At design time you can also create special types of your own in the TpFIBTransaction editor and use them as internal ones. Set the transaction type to set its 
parameters:

TpbDefault – parameters must be set in TRParams
tbpReadCommited – shows the ReadCommited isolation level
tbpRepeatableRead – shows the RepeatableRead isolation level 

How to use TpFIBDatabase FIBPlus Component to connect with Firebird database in Delphi XE4?

How to use TpFIBDatabase FIBPlus Component to connect with Firebird database in Delphi XE4?

TpFIBDatabase component is used to make database connectivity with Firebird database in Delphi. For using TpFIBDatabase component, you should have FIBPlus and Firebird installed on your system. I am using Delphi XE4, Firebird 2.5.2 and FIBPlus 7.5 to make database connection.

Connection parameters are typical for InterBase/Firebird server:

1) path to a database file;
2) user name and password;
3) user role;
4) charset;
5) dialect;
6) client library (gds32.dll for InterBase and fbclient.dll for Firebird).

To connect to a database you should call the Open method or set the Connected property to True. It’s also possible to use this code to connect to a database:

function Login(DataBase: TpFIBDatabase; dbpath, uname, upass, urole: string): Boolean;
begin
 if DataBase.Connected then DataBase.Connected := False; 
 with FDataBase.ConnectParams do begin
   UserName := uname;
   Password := upass;
   RoleName := urole;
 end;
 DataBase.DBName := dbpath;
 try DataBase.Connected := True;
 except
   on e: Exception do
   ShowMessage(e.Message);
 end;
 Result := DataBase.Connected;
end;

To close the connection either call the Close method or set the Connected property to False. 

You can also close all datasets and connected transactions at once:

procedure Logout(DataBase: TpFIBDatabase);
var i: Integer;
begin
  if not DataBase.Connected then
  Exit;

  for i := 0 to DataBase.TransactionCount - 1 do
    if TpFIBTransaction(DataBase.Transactions[i]).InTransaction then 
      TpFIBTransaction(DataBase.Transactions[i]).Rollback
 DataBase.CloseDataSets;
 DataBase.Close;
end;

Friday, 27 September 2013

Firebird Basic Interview Questions and Answers

Firebird Basic Interview Questions and Answers

If you are going to appear in a firebird technical interview, you must go through following basic firebird interview questions and answers. These are very basic questions on firebird database like general introduction to firebird, features of firebird database, similarities and differences between firebird and interbase, IBExpert tool for Firebird, firebird database connectivity etc. Following are the firebird interview questions and answers.

1. What do you know about Firebird database?

You should know general things about the Firebird database like: 

A) Firebird is open source database
B) It runs on Windows, Linux and Unix
C) Some Facts, Figures and Features of Firebird database

Read more for further details...

2. What are the various features of Firebird database?

You should be aware of the features and functionalities Firebird database provides like:

1. Firebird supports multiple platforms like Windows, Linux and Unix
2. Multi-generation architecutre of Firebird database
3. Powerful and developer-friendly SQL language
4. Logging and monitoring features of Firebird database
5. Security and Performance of Firebird and much more.

Read more for further details...

3. What is the difference and similarities between Firebird and Interbase databases?

You must prepare this interview questions because Firebird and Interbase databases are closely related. There are a lot of difference and similarities between Firebird and Interbase databases. I have written a complete article on this. You can access it here.

4. What is IBExpert?

IBExpert is a professional Integrated Development Environment (IDE) for the development and administration of InterBase and Firebird databases. IBExpert includes many coding tools and features: visual editors for all Database Objects, an SQL Editor and Script Executive, a Debugger for Stored Procedures and Triggers, a Query Builder, a powerful Database Designer and much, much more...

5. How to connect with Firebird database in Delphi using TSQLConnection?

This question is related to Delphi developers. TSQLConnection component is used to connect with firebird in Delphi. Below is code snippet for making firebird database connection in Delphi.

begin
  SQLConnection1.ConnectionName := 'Devart InterBase';
  SQLConnection1.DriverName := 'DevartInterBase';
  SQLConnection1.GetDriverFunc := 'getSQLDriverInterBase';
  SQLConnection1.Params.Values['LibraryName'] := 'dbexpida40.dll';
  SQLConnection1.Params.Values['VendorLib'] := 'fbclient.dll';
  SQLConnection1.Params.Values['HostName'] := 'hostname';
  SQLConnection1.Params.Values['Database'] := 'databasename';
  SQLConnection1.Params.Values['User_Name'] := 'username';
  SQLConnection1.Params.Values['Password'] := 'password';
  SQLConnection1.LoginPrompt := False;
  SQLConnection1.Open;
end;

6. Have you ever found the compiler error "Unsupported on-disk structure for file xxx.fdb" while working with Firebird database?

This is the common error occurs in most of the cases when you are using both firebird and interbase. Sometimes mismatch happens between gds32.dll (interbase driver dll) and fbclient.dll (firebird driver dll) which causes this error. There is detailed solution of this error discussed here.

Beside all the above firebird interview questions and answers, you should prepare general database concepts like joins, index, query optimization, stored procedures and functions, triggers, cursors etc. 

Wednesday, 25 September 2013

List of Errors and Compiler Warnings while code migration from Delphi 7 to Delphi XE4 - Part 1

List of Errors and Compiler Warnings while code migration from Delphi 7 to Delphi XE4 - Part 1

I had to migrate a Delphi 7 application to the Delphi XE4. While migrating my Delphi 7 application to Delphi XE4, I encountered a lot of compiler errors, warnings and hints. I made a list of all the compiler errors and warning with their solutions which I got during migration from Delphi 7 to Delphi XE4. I think I should share my list and experience with all you Delphi guys. 

Basically, you will get all these compiler errors and warnings when you are migrating the code from your Delphi application which is earlier than Delphi 2009 to Delphi 2009 or the higher versions of Delphi. Most of the errors are related to unicode strings. Delphi 7 does not support unicode because unicode support in Delphi was introduced in Delphi 2009.

Here goes my list of errors and compiler warnings which I got and resolved during Delphi 7 to Delphi XE4 code migration.

1. Mismatched datatypes like AnsiChar / AnsiPChar / AnsiString 

In my Delphi 7 code, a lot of AnsiChar, AnsiPChar and AnsiString keywords were used which were causing problems. So I converted them to WideChar (Char), Unicode String (String) and WidePChar (PChar) for unicoding.

2. Index 0 is not accessible in string

In Delphi 7, there is 0 based string indexing while in Delphi XE4, there is 1 based string indexing. So wherever 0 index of string was used, I had to use 1 index.

3. NoMetadata property does not exist

In Delphi 7, TSQLDataset has property NoMetadata which if set to true, no metadata is loaded. Similar property in Delphi XE4 is GetMetadata which if set to false, no metadata is loaded.

So, I replaced all NoMetaData = True lines to GetMetadata = False and the error got resolved.

4. DBXpress component was not found

DBXpress is deprecated and its functionality is included in SqlExpr. So I removed DBExpress from uses.

5. TMsgDlgBtn enum was causing compilation errors

TMsgDlgBtn enum (Message Dialog) has 12 elements in Delphi XE4 while in Delphi 7, there are only 11 elements. New element is mbClose. So added mbClose in the enums.

6. Shortstring (string[n]) datatypes were throwing errors

Shortstring (string[n]) datatype is deprecated in Delphi XE4 but is there for backward compatibility. So you can still use shortstring in Delphi XE4 but its ANSI not unicode.

I was using firebird 2.5.2 database. I also got some error related to that:

7. %1 is not a valid Win32 application

I had installed 32-bit Delphi XE4 and 64-bit Firebird 2.5. Because of this, I was getting the mentioned error while connecting to the database through Delphi XE4. I uninstalled 64-bit Firebird, downloaded and installed 32-bit Firebird and the problem was resolved. 

8. Following errors were coming in while executing firebird database queries from Delphi XE4

invalid Token
invalid request BLR at offset 163 
function F_ANYFUNCTION is not defined     
module name or entrypoint could not be found

Earlier I was using Firebird 2.5.1. Now I had migrated to Firebird 2.5.2. I looked in the Firebird 2.5.1 configuration file and made similar changes in firebird 2.5.2 configuration file.

ExternalFileAccess = Restrict (path of database file)

Also added udf.dll in UDF folder of Firebird 2.5.2

9. Unknown Driver - DevartInterbase

My Delphi 7 was using DevartInterbase driver in one of the TSQLConnection component. But now when I migrated to Delphi XE4, I was getting the above error. To solve this I downloaded the latest version of devart interbase for Delphi XE4 and the problem was resolved.

10. Unsupported on-disk structure for file mydatabase.fdb

When we installed latest version of devart interbase, by default it was using gds32.dll which is for interbase database. I just replaced VendorLib property of TSQLConnection from gds32.dll with fbclient.dll and the problem was resolved.

11. 'SQLDataSet: Type mismatch for field 'NAME', expecting: String actual:WideString'

When I installed latest devart interbase driver to support Delphi XE4 unicode version, I got this error in TSQLConnection component. 

I found 2 solutions for this error:

A) Set UseUnicode property of TSQLConnection to False.
B) Replace all TStringField with TWideStringField

12. interbase is not licensed

As I downloaded the developer free edition of devart interbase, it was giving this error. To resolve this error, Firebird and Interbase databases have to be restarted every 24 hour. Afterwards I got enterprise edition of devart.

13. Cannot perform operation – DB is not open

While connecting to database, firebird library name and path (fbclient.dll) was missing. Added fbclient.dll path and problem was resolved.

14. “EurekaLog Error” - project post processing has failed

Delphi 7 was using EurekaLog 6. But now I was using EurekaLog 7. So to handle the error, I went in Project –> Eurekalog options –> activated eurekalog and changed project type to old eurekalog application.

Rebuilt and compiled the application and error was gone.

15. When opened Delphi 7 application in Delphi XE4 RAD Studio, I noticed that all the dfm files had changed. The changes which I noticed were like:

Width = 443 --changed in Delphi XE4
Height = 277 --changed in Delphi XE4
ExplicitWidth = 443 --added automatically in Delphi XE4
ExplicitHeight = 277 --added automatically in Delphi XE4

These are the changes which RAD Studio introduces itself in the dfm files when you open it first time. You can ignore these changes or accept it for the first time.

I will come up with more compiler errors and warnings which I got during Delphi 7 to Delphi XE4 code migration in second part of this post.

Wednesday, 18 September 2013

Interbase (IB) vs Firebird (FB): Differences and Similarities between Interbase and Firebird

Interbase (IB) vs Firebird (FB): Differences and Similarities between Interbase and Firebird

There are a lot of differences and similarities between Interbase and Firebird. I have tried to compare both Interbase and Firebird in my way (Interbase vs Firebird).

Interbase and Firebird are two different database servers. Firebird has originated from Interbase. After the release of Interbase 6.0 in 2000, developers moved away from Interbase and made first freeware and open-source version of Interbase and named it Firebird 1.0, made it available on SourceForge. Up to this point, all the features of Interbase and Firebird were same but after this different team started working on their products (Interbase and Firebird).

Following are the differences between Interbase and Firebird:

1. Firebird is freeware and open source while Interbase is commercial and  is currently developed and marketed by Embarcadero Technologies. So Firebird as being freeware and open source, the community members can change/modify anything in the source code and all other users of Firebird will be benefitted of that. 

2. Delphi supports officially only Interbase, however drivers probably work with basic functions and there are free and paid drivers and libraries available for Firebird. With Enterprise and Architect Editions of Delphi XE4, Firebird drivers are also supported. Delphi works well with Interbase using two different sets of access components. Interbase Express provides specific support for Interbase only. It does not support Firebird. Database Express, a more generic set of components for various databases, is also part of Delphi and supports both Interbase and Firebird. IBX is usually preferred over DBX for Delphi access to Interbase.

3. In Firebird, there is an embedded version so you don't need a real server - single user "server" is embedded into Delphi (Win) or Lazarus/FreePascal (Win/Lin) executable.

4. Interbase and Firebird DLLs: Usually we use gds32.dll to connect with interbase database server and fbclient.dll to connect with firebird server.

5. Latest Releases of Interbase and Firebird: 

InterBase XE is the latest version of Interbase which was released in 2010. Interbase XE new features include a 64 bit client and server, improved security, improved scalability, support for dynamic SQL in stored procedures, and optimized performance of large objects with stream methods.

Firebird 2.5.2 is the current stable version. New features included in this Firebird release are improved multithreading, regular expression syntax and the ability to query remote databases. The planned 3.0 release is expected to support stored procedures in languages such as Java and C++, and SQL window functions that restrict query results. An alpha version was released in August 2013.

Wednesday, 7 August 2013

Firebird: Free and Open Source Database Server

Firebird: Free and Open Source Database Server

Firebird is a free and open source relational database offering many ANSI SQL standard features that runs on Linux, Windows, Mac OS X and a variety of Unix platforms. Firebird offers excellent concurrency, high performance, and powerful language support for stored procedures and triggers. Firebird technology has been in use for 20 years, which makes it a very mature and stable product. Following is the list of features which Firebird provides:

1. Free and Open Source

Firebird is free like a bird. No fees for download, registration, licensing or deployment, even you distribute Firebird as part of your commercial software package. Anyone can build a custom version of Firebird, as long as the modifications are made available, under the same IDPL licensing, for others to use and build on.

Firebird's development depends on voluntary funding by people who benefit from using it. Funding options range from donations, through Firebird Foundation memberships to sponsorship commitments.

2. Firebird Supported Platforms

Firebird 2.5 runs on Windows (32- and 64-bit), various Linux versions (32- and 64- bit), Solaris (Sparc and Intel), HP-UX (PA-Risc) and MacOS X. Main development is done on Windows and Linux, so new releases are usually offered first for these platforms, followed by other platforms after a few weeks.

3. Firebird Architecutres and Versions

Firebird comes in a number of flavors: Classic, SuperClassic, SuperServer and Embedded. Latest release of Firebird are:

Firebird 3.0
Firebird 2.5
Firebird 2.1

Firebird 3.0 is available only for testing and not for production environment. Firebird 2.5 is the stable release.

4. Firebird Database Connectivity

Firebird is supported by numerous database connectivity options:

Firebird.NET
JayBird (Java)
Delphi/C++ Builder drivers (Embarcadero Delphi/C++ Builder IDEs include dbExpress drivers to work with Firebird.)
FreePascal & Lazarus
PHP for Firebird
FireRuby

and more.....

5. Firebird Administration Tools

Firebird comes with a number of powerful command-line tools to administer the database, but does not include a GUI interface. Fortunately, third-party GUI administration tools are available.

6. Firebird Codebase

Work on porting the codebase from C to C++ began in 2000. On 23 February 2004, Firebird 1.5 was released, which was the first stable release of the new codebase.

7. Firebird Documentation

The Firebird Project supplies users, developers and administrators with various kinds of documentation, from Quick Start guides to expert-level articles devoted to various aspects of Firebird.

There are a lot of papers, FAQs and articles that you may want to check in the Firebird main site. Also, you can check if your country has a localized community site or discussion list, so you can get support in your native language.

All this information can be found digging around in the Firebird main site. Also, check www.firebirdnews.org to get up to date with the most recent news related to Firebird.

8. Firebird Community Support

Firebird has large community around the world, where people will be glad to help newbies and experienced developers to get answers for almost all tricky questions.