Saving Files to a Database using Delphi: Saving Bitmaps to a Database
In this series of articles I will discuss how to save and retrieve images and binary files to and from a database and recognize the format by reading the first four bytes of blob data. As usual I am using Borland Developer Studio 2006 (Delphi 2006) as the development platform and for the database server I will use MS SQL Server 2000. I intend to start from scratch and demonstrate how easily and quickly a database application can be created in Delphi by using its Data Access and Data-Aware components.
Saving Files to a Database using Delphi: Saving Bitmaps to a Database (Page 1 of 4 )
In fact, you can create a simple but fully functional database application in Delphi without writing a single line of code! I will take you through a step by step demonstration of how to create a rudimentary database application in Delphi using data-aware components to save and retrieve bitmaps and other files to and from a database server and how to recognize the format of blob data by checking its first four bytes.
The very first thing we need to do is create a blank database called TestDB in the remote MS SQL server. You can use any other existing database on any other server but you will have to make sure that it has a blob field in one of its tables where you can save the image. My TestDB contains just one table with three fields: a primary key field, a BLOB field and a text field for image description. This is the SQL script used to create the table:
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ImgTbl]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
If you are using an older version of Delphi which requires you to access the database through BDE (Borland Database Engine) only, or for some reason you are using dbExpress (a simple and thin data-access layer providing connectivity to SQL database servers with the help of native drivers) to connect to the server, you have to make sure that a valid ODBC DSN(Data Source Name) has been created for the database and add that DSN in the dbExpress connections. If a valid DSN doesn't exist you can create one from the ODBC Administrator in the control panel.