--> Connection to the Database When Run-Time | Delphi Tips Trick

For Newbie

Friday 18 November 2011

Connection to the Database When Run-Time

| Friday 18 November 2011
I finally had a chance too for updates of this blog. This time I want to share about how to connect to the database (Ms. Access) at run-time information on Delphi programming. Run-time means when the program starts, not when the design (design time). The advantage that we make the program more dynamic and we can make changes to the connection when the program is running.
For example, create a database using Ms. Access course, and do not forget to add some sample data in it. To be more afdhol, add a password on that database. Then go to your Delphi and create a new palikasi. Make sure you keep a folder with the database program. To connect to the database, we will use ADO. Add the following components on your form. Are in parentheses is the name of the tab where the component is located.

    
ADOConnections (ADO)
    
ADOTable (ADO)
    
DataSource (Data Access)
    
DBGrid (Data Controls)
Property 'name' of each component do not need to be replaced, let alone the name of the default. Navigate property 'Connection' from ADOTable1 to 'ADOConnections1', then to select ADOTable1 DataSource1 component in the properties 'DataSet' and to DBGrid1 select DataSource1 on property 'DataSource'. Well now all components are connected to each other, but why the data has not yet appeared in DBGrid? Yes it is so because we do not connect to it with the database. The new connection will be made when the program starts. To this add the following script on the event 'onCreate' your form
TForm1.FormCreate procedure (Sender: TObject); const
 
db_name = 'data.mdb';
 
passdb ='';
 
table = 'tb_name'; begin
  
ADOConnection1.ConnectionString: =
  
'Provider = Microsoft.Jet.OLEDB.4.0;' +
  
'Data Source =' + ExtractFilePath (application.ExeName) +db_name + ';' +
  
'Persist Security Info = False;' +
  
'Jet OLEDB: Database Password =' ​​+ passdb;
  
ADOConnection1.LoginPrompt: = false;
  
ADOConnection1.Connected: = True;
  
ADOTable1.TableName: = table;
  
ADOTable1.Active: = true; end;
Notice in the script above there are three constants each 'namadb' is the name of your database, 'passdb' is the password database, and 'table' is the name of the table in the database. So you need to change its value according to your database.
Because the location of the database is a folder with the program, then in the data source to add the function 'ExtractFilePath (application.ExeName)' to generate the path of the program exe file is located. That way the program is placed anywhere as long as it is a folder with the database then the connection will still point to that database.
Try running your program. If the existing data in the database appear in the DBGrid it works ...

Related Posts

No comments: