Lazarus and MS Access
Lazarus and MS Access
Lazarus and MS Access
Pgina 1
Home - - A2 Databases - - A2 Scripts - - A2 Problems - - AS Hardware - Database Tutorials - - Lazarus Tutorials - - Lazarus - - Linux - -
Top
Introduction
A Lazarus program can modify, interrogate and view the contents of an existing MS Access database. This tutorial is a step-by-step guide. However, it is worth looking at the layout of the Form and the source code now. They are at the end of this document. I am working with Lazarus 0.9.28.2 beta in MS Windows. You will connect using components from the SQLdb component palette. This comes with Lazarus. This palette has no specific Access components but it is easy to connect using the ODBC components. ODBC stands for Open DataBase Connect
Top
Preparations
Create a folder called AccessConnect. To save a Lazarus application into the folder Click File/New/Application and the familiar Form1 should appear Click File/Save All and navigate to your AccessConnect folder Click Save (for the unit) and Save (for the project). Click the green run icon and check that a blank form appears Close the blank form.
http://www.alevel-computing.x10.mx/TutorialLazarusAccess.php
04/04/2013 22:47:20
Lazarus and MS Access Lazarus is ready. You need to create an MS Access database beforehand. My database is called A.db. See Appendix A. A.db does not need to be in the same folder as your Lazarus project. It just needs to exist. You need to set up a DSN connection to your Access database beforehand. This sounds hard but is easy. I called mine 'LazConnect'. See Appendix B. Everything is now in place. Summary You need A Lazarus project in a folder called AccessConnect A MS Access database called A.db - Student(StudentID , First, Second) A DSN connection to your database. I called mine LazConnect
Pgina 2
Top
http://www.alevel-computing.x10.mx/TutorialLazarusAccess.php
04/04/2013 22:47:20
Lazarus and MS Access Close the form. Summary Components on the form ODBCConnection1 SQLTransaction1 SQLQuery1 Datasource1 DBGrid1 Button1 : caption = 'Connect'
Pgina 3
Top
Connecting
You now set up the connection between the program and the database. When you click the button Connect then a connection to a.db, (the Access database) is made and the data from your database will appear in the DBgrid. Here is how: Double-click the button. The source editor appears. In the Button1click procedure add the following code: procedure TForm1.Button1Click(Sender: TObject); begin ODBCConnection1.DatabaseName:='LazConnect'; ODBCConnection1.UserName:='Admin'; ODBCConnection1.Transaction:=SQLTransaction1; SQLTransaction1.Database:=ODBCConnection1; SQLQuery1.Database:=ODBCConnection1; SQLQuery1.Transaction:=SQLTransaction1; SQLQuery1.UsePrimaryKeyAsKey:=False; SQLQuery1.SQL.Text:='SELECT * FROM Student'; Datasource1.dataset:=SQLQuery1; DBGrid1.DataSource:=DataSource1; end; This code Tells the TODBCConnection the name of the database and the transaction Tells the TSQLTransaction the name of the TODBCConnection Tells the TSQLQuery the name of the TODBCConnection and the TSQLTransaction. Tells the datasource the name of TSQLQuery Tells the DBGrid the name of its datasource You can see that it prepares a route from the database to the DBGrid. It also prepares (but does not execute) a query to get all the data from the database using SELECT * FROM Student The line about Primary Keys is necessary as there is a bug in MS Access ODBC driver and this avoids it. Run the program. Click the button There should be no errors. You should see the same as before. If the program doesnt run or there is an error when you click the button then you must stop and check everything. It is pointless to proceed since this problem is going to block you every time.
http://www.alevel-computing.x10.mx/TutorialLazarusAccess.php
04/04/2013 22:47:20
Lazarus and MS Access Add a label to Form1. The TLabel component is in the 'Standard' component palette. This label will change to show you are connected when you connect. To do this, add the 5 lines that are highlighted just before the end; Datasource1.dataset:=SQLQuery1; DBGrid1.DataSource:=DataSource1;
Pgina 4
ODBCConnection1.Open; If ODBCConnection1.Connected then begin Label1.caption:='connected -great'; end; end; Rerun the program Click the button Connected to Access database great should appear in the label. If the label doesnt change then you must stop and check everything. It is pointless to proceed since there is no connection. Next add the one line of code immediately after the code you just wrote and just before the end of the procedure: SQLQuery1.open; This single line executes the query that was prepared earlier. The table of results is stored in SQLQuery1 Select * from Student is passed to the TODBCConnection and then to the database and the result is passed back through the chain to the TSQLQuery, the datasource and into the DBGrid. Run the program It should compile without errors Click the button The label should say 'Connected to Access database - great' The DBGrid should fill up with the data from your database. If it does then that is great. You can go on. If it doesnt then you must stop and check everything. It is pointless to proceed since there is no connection. Summary Components Label1 Procedures Button1.Click Initialise components Connect Open Query
Top
SELECTing data
You can interrogate the data in the database using SELECT.
http://www.alevel-computing.x10.mx/TutorialLazarusAccess.php
04/04/2013 22:47:20
Lazarus and MS Access Add a new button (Button2) and in the Object Inspector change the buttons caption to SELECT. Also add an editbox (Edit2) onto the form so that the user can enter their SELECT command. It needs to be fairly wide. Add the procedure below procedure TForm1.Button2Click(Sender: TObject); begin SQLQuery1.Close; SQLQuery1.SQL.text:=edit1.text; SQLQuery1.Open; end; Closing SQLQuery1 clears the contents in preparartion for a new query. Then the new query is loaded. Then the new query is executed and the table of results made available in SQLQuery1. Run the program. Click the Connect button Check that the data appears in the DBGrid Enter SELECT First FROM Student; Click the Select button The list of first names only should appear in the DBGrid. Summary Components Button2 : caption = 'SELECT' Editbox1 Procedures Button2.Click Deactivates the SQLQuery1 Copies the query from the edit box into SQLQuery Executes the Query Reactivates SQLQuery
Pgina 5
Top
http://www.alevel-computing.x10.mx/TutorialLazarusAccess.php
04/04/2013 22:47:20
Lazarus and MS Access INSERT INTO Student VALUES (23, Fred,Jones); then this will enter Fred Jones as student 23 into the database. Run the program Click the connect button Add the above In the editbox Click the Insert button. Enter in the select edit box - SELECT * FROM Student; Click the select button the new entry in the DBGrid. Close the application. Summary Components Button3 : caption='INSERT' Editbox2 Procedures Button3.Click Inserts data directly
Pgina 6
Top
Lazarus and MS Access Click the select button Check the new entry is in the DBGrid. Close the application. Summary Components Button3 : caption='INSERT' Editbox2 Procedures Button3.Click Insert data with SQLQuery
Pgina 7
Top
http://www.alevel-computing.x10.mx/TutorialLazarusAccess.php
04/04/2013 22:47:20
Lazarus and MS Access Procedures Button4.Click Runs SQLQuery1 Cycles through the database table in SQLQuery1 Creates a formatted string of the contents of each row Puts the string into the memo box.
Pgina 8
Top
DELETE data
The method for deleting data is easy. Remember that the code for INSERT isn't just for INSERT but for any SQL command that does not return a result from the database. DELETE is just such a command. Therefore the code for DELETE is identical to the code for INSERT. Therefore you can enter a DELETE command in the INSERT edit box and it will work Remember to then run 'SELECT * FROM Student' in order to see the effect. The SQL command DELETE FROM Student WHERE StudentID=23 will delete student 23 Fred Jones from the database . To test this out write Run the program Click the connect button Add the above in the Insert editbox Click the Insert button. Enter in the select edit box - SELECT * FROM Student Click the select button Check the entry has gone from the DBGrid. Close the Form. To get a 'good' DELETE button you would first have the code for INSERT and then have the code for opening the query 'SELECT * FROM Student' after it. Then the result will then appear instantaneous.
Top
Appendix A
Getting SQLite3.exe The program can be obtained from the SQLite website . It can be installed and run on a memory stick (flash drive).
Top
Appendix A
Getting MS Access MS Access is not open-source or free software. It is copyrighted by Microsoft. It is not a standard part of Microsoft Office but is available on the Professional version
Top
Appendix B
Creating a simple ACCESS database called A.db
http://www.alevel-computing.x10.mx/TutorialLazarusAccess.php
04/04/2013 22:47:20
Lazarus and MS Access You need to create an MS Access database. My database is called A.db, and it has one table called Student, with three columns - StudentID(number), First (text) and Second(text). There are three rows in the table. The SQL code for the table is below. I dont know how to import SQL into Access. If you do know how, then import the SQL below, otherwise you will have to create the database by hand in Access. Use the details in the SQL code to get the correct fields etc. -- SQL for the Student table CREATE TABLE Student( StudentID INTEGER PRIMARY KEY NOT NULL, First VARCHAR(20), Second VARHAR(20)); -- Some Student Values INSERT INTO Student VALUES (1, David, Beckham); INSERT INTO Student VALUES (2, William, Shakespeare); INSERT INTO Student VALUES (3, Reginald, Dwight);
Pgina 9
Top
Appendix C
Setting up a DSN connection This is easy but you need access to the C drive. Therefore this will need the administrator in many schools. You need to find Administrative Tools/Data Sources (ODBC). This may be on Control Panel or Start /Programs/ Administrative Tools/Data Sources (ODBC) Once you have found it then Click on the System DSN tab Click on Add Choose Microsoft Access Driver (*.mdb) Click Finish Fill in the Data Source Name edit box with LazConnect Click Select Navigate to your database called a.db Click OK The link between LazConnect and A.db is made.
Top
http://www.alevel-computing.x10.mx/TutorialLazarusAccess.php
04/04/2013 22:47:20
Pgina 10
Top
Source Code
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, odbcconn, sqldb, db, FileUtil, LResources, Forms, Controls, Graphics, Dialogs, DBGrids, StdCtrls; type { TForm1 } TForm1 = class(TForm) Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; Datasource1: TDatasource; DBGrid1: TDBGrid; Edit1: TEdit; Edit2: TEdit; Label1: TLabel; Memo1: TMemo; ODBCConnection1: TODBCConnection; SQLQuery1: TSQLQuery; SQLTransaction1: TSQLTransaction; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); private { private declarations } http://www.alevel-computing.x10.mx/TutorialLazarusAccess.php 04/04/2013 22:47:20
Lazarus and MS Access public { public declarations } end; var Form1: TForm1; implementation { TForm1 } procedure TForm1.Button1Click(Sender: TObject); begin ODBCConnection1.DatabaseName:='LazConnect'; ODBCConnection1.UserName:='Admin'; ODBCConnection1.Transaction:=SQLTransaction1; SQLTransaction1.Database:=ODBCConnection1; SQLQuery1.Database:=ODBCConnection1; SQLQuery1.Transaction:=SQLTransaction1; SQLQuery1.UsePrimaryKeyAsKey:=False; SQLQuery1.SQL.Text:='SELECT * FROM Student'; Datasource1.dataset:=SQLQuery1; DBGrid1.DataSource:=DataSource1; ODBCConnection1.Open; If ODBCConnection1.Connected then begin Label1.caption:='connected -great'; end; SQLQuery1.open; end; procedure TForm1.Button2Click(Sender: TObject); begin SQLQuery1.Close; SQLQuery1.SQL.text:=edit1.text; SQLQuery1.Open; end; procedure TForm1.Button3Click(Sender: TObject); begin //Not now needed - we will use SQLQuery1 instead // SQLTransaction1.commit; //SQLTransaction1.StartTransaction; //ODBCConnection1.ExecuteDirect(edit2.text); //SQLTransaction1.commit; SQLQuery1.Close; SQLQuery1.SQL.text:=edit1.text; SQLQuery1.ExecSQL; end; procedure TForm1.Button4Click(Sender: TObject); begin SQLQuery1.Close SQLQuery1.SQL.Text:='Select * FROM Student'; SQLQuery1.Open;
Pgina 11
http://www.alevel-computing.x10.mx/TutorialLazarusAccess.php
04/04/2013 22:47:20
Lazarus and MS Access while not SQLQuery1.Eof do begin memo1.lines.add( ' ID: ' + SQLQuery1.FieldByName('StudentID').AsString + ' First name: ' + SQLQuery1.FieldByName('First').AsString + ' Second name: ' + SQLQuery1.FieldByName('Second') .AsString) ; SQLQuery1.Next; end; end; initialization {$I unit1.lrs} end.
Pgina 12
http://www.alevel-computing.x10.mx/TutorialLazarusAccess.php
04/04/2013 22:47:20