Sign in Join
Wiki copytemporary

SQLdb Tutorial1: what changed

Revision 1 to 2. Removed lines have a minus sign; added lines have a plus sign.

OldNewLine
11## Introduction
22
33This tutorial shows you how to program databases using practical example code based on the [[SQLdb Package]]. It is primarily targeted at newbies. If somebody is looking for basics about databases and SQL, he should read relevant books/documentation. For this tutorial I use Firebird with the example database employee.fdb. Other databases can also be used; some adjustments will need to be made which are mentioned in the text.
44
55While this tutorial may seem long, it mostly is just a lot of text that explains why you should type what you type. As you can see at the end, the amount of actual code you will need for a working application is not that great. More experienced developers will hopefully be able to glance through the instructions and quickly understand what's going on. Also, you can stop at the end of the Basic example chapter and have a working program.
66
77This tutorial is based on a [[SQLdb Tutorial1/de|German tutorial]] by Swen, but it is extended, especially after the Basic example. Swen wants the German version to remain as-is. If this is a problem, we can rename this version and base a new German translation on that.
88
99From Swen: thanks to Joost and Michael. Without their help this tutorial probably never would have come about.
1010
1111## Requirements
1212
1313This tutorial is written for use with recent Lazarus versions (Laz 1.0); it should also work on older versions Lazarus 0.9.30.
1414
1515Please see [[SQLdb Tutorial0]], which will walk you through making sure you have the right sample database set up.
1616
1717## Basic example
1818
1919### Project and components
2020
2121First you should create a new Lazarus project.
2222
2323To get access to our database we need one [[TIBConnection]], one [[TSQLTransaction]] and one [[TSQLQuery]] component from the '[[SQLdb tab]]' in the component palette:
2424
25-<figure>
26-<img src="sqldbcomponents.png‎" title="sqldbcomponents.png‎" />
27-<figcaption>sqldbcomponents.png‎</figcaption>
28-</figure>
25+![](/wiki-images/c/c5/Sqldbcomponents.png%E2%80%8E)
2926
3027[[TIBConnection]] is an Interbase/Firebird specific connection component. If you are using a different database, substitute the proper component from the '[[SQLdb tab]], e.g. a [[TSQLite3Connection]]' for an SQLite database, [[TPQConnection]] for a PostgreSQL database. Discussion of setting up any database access libraries is out of scope for this tutorial; see e.g. [[Databases]] for that.
3128
3229Click on the [[TIBConnection]] (or equivalent connection component) on your form, and in the Object Inspector, change the name to *DBConnection*. This will simplify the rest of the tutorial when using different databases. It's also generally a good idea to name your components for something useful in your program (e.g. MainframeDBConnection) so you know what it stands for.
3330
3431The other two components, [[TSQLTransaction]] and [[TSQLQuery]], can be used for all databases that are supported by SQLdb.
3532
3633To display the data, we use a [[TDBGrid]] component, which can be found on the 'Data Controls' tab. To connect this component to the database components we need a [[TDataSource]] component from the '[[Data Access tab]]'.
3734
3835Now we have all database components needed for the first example. You can enlarge the TDBGrid to have enough space to display all data.
3936
4037### Link the components
4138
4239Next we need to connect our components. A very simple way is to use the object inspector, but you can also do this in your source code.
4340
4441Change the *Transaction* property of DBConnection to 'SQLTransaction1'. This causes the *Database* property of SQLTransaction1 to automatically change to 'DBConnection'.
4542
4643Then, change the *Database* property of SQLQuery1 to 'DBConnection'. Lazarus automatically adds the value for the 'Transaction' property.
4744
4845Next, change the *Dataset* property of Datasource1 to 'SQLQuery1'.
4946
5047Finally we change the *Datasource* property of DBGrid1 to 'Datasource1'.
5148
5249We now end up with a connection that links its default transaction to a transaction component. The transaction component links its database property to the connection object. These two components are enough to connect and execute instructions, but not enough to show queries. For this, an SQLQuery component is used, which points to the database (and links to its default transaction). With the SQLQuery, we'll later on retrieve data and post it back to the database.
5350
5451Finally, the datasource component, which is linked to the query component, is a sort of place holder. It keeps track of where in the query dataset we are and the GUI components are linked to that so they all show the same record.
5552
5653If this is gibberish to you, don't despair: with just some more work, we'll be able to show our first data.
5754
5855### Connecting to the database
5956
6057How can we now show the data from our database on the screen?
6158
6259First we need to tell DBConnection where the employee.fdb database is located. Locations of that db differ depending on operating system, it could be something like:
6360
6461- .../examples/empbuild/ subdirectory of your Firebird installation on Linux
6562- C:\Program Files\Firebird\Firebird_2_5\examples\empbuild\EMPLOYEE.FDB on a Windows machine
6663- Using Firebird embedded, the file should be in your project directory
6764
6865Again you have the choice: you can use the object inspector to assign the path or do it directly in your source code.
6966
7067We choose to use the object inspector: set the DBConnection 'HostName' property to the Firebird server name or IP adddress. Use localhost if a Firebird server is running on your development machine; use a blank value if you use the embedded Firebird client. Change the *DatabaseName* property of DBConnection to the path to the employee.fdb file on the database server. If you use embedded Firebird, the path part should be empty and you should just specify the filename.
7168
7269Before the database server grants access to the data, it will check authorisation via username and password. A serious database application will ask the user for both values when the application is started, and send these to the server when connecting. A possible way of doing this is shown in [[SQLdb Tutorial3]].
7370
7471However, for now, to simplify matters, we use the object inspector again to hard code these. Change the 'UserName' property to 'SYSDBA' and 'Password' to 'masterkey' (of course, adjust if your database installation has a different username/password).
7572
7673Now check if all settings so far are correct: set the 'Connected' property to 'True'. If the database path isn't correct or if username or password are wrong, you will get an error message. If the connection was successful, you should cut it now (set 'Connected' to 'False').
7774
7875#### PostgreSQL
7976
8077The situation with PostgreSQL is very similar to that on Firebird. The database name does not have a path - you just specify a name part (e.g. 'employee'). PostgreSQL has no embedded mode, so you need to fill out the *HostName* property for the connection test to work.
8178
8279#### SQLite
8380
8481For SQLite, you can leave the 'HostName', 'UserName', and 'Password' properties empty. Set the 'DatabaseName' to the name of your SQLite file, e.g. employee.sqlite. Note: sqlite will create the database specified if it doesn't exist, so be careful here.
8582
8683You should now have something like the following screenshot - todo: this screenshot is actually further along, we only have a button now: [framed|center|Form and components set up](/wiki-images/b/b2/SQLTut1ComponentsSetUp.png)
8784
8885Change the property *Options* → *dgDisplayMemoText* of the DBGrid to '(True)'. Otherwise you will see (MEMO) in all the data fields.
8986
9087### Choosing what data to show
9188
9289Although the connection was successful, no data was displayed. The reason is simple. We haven't told the database server which data to return: the employee.fdb database contains several tables, and we haven't told Firebird the table we want to see. If you don't know the structure of a database, you can use tools like [FlameRobin](http://www.flamerobin.org/index.php), to display the contents. Lazarus also provides such a tool - the [[DataDesktop]]. You can find it in the /tools/lazdatadesktop/ subdirectory of Lazarus. Save our project and then open the project lazdatadesktop.lpi and compile it.
9390
9491[framed|center|The DataDesktop in action](/wiki-images/d/da/DataDictonary1.png)
9592
9693Back to our example.
9794
9895We want to display all data from the table 'CUSTOMER'. The SQL instruction for that is:
9996
10097``` sql
10198select * from CUSTOMER
10299```
103100
104101We need to assign this command to the 'SQL' property of SQLQuery1. In the source code of our project this would look like:
105102
106103``` pascal
107104SQLQuery1.SQL.Text := 'select * from CUSTOMER';
108105```
109106
110107The SQL instruction must be enclosed by single quotes. You also have the ability to assign the content of another component (e.g. Edit1.Text). This is not always a good idea; see [[Secure programming]] (a more advanced text) for details on SQL injection.
111108
112109Let's add a *TButton* from the 'Standard' tab on the form. When the user clicks on the button, data retrieval should start. Change its *Caption* property from "Button1" to Show data".
113110
114111We will need some code for this. Double click on Button1. Lazarus then creates the skeleton of the necessary procedure. In our source code we should find the following lines:
115112
116113``` pascal
117114procedure TForm1.Button1Click(Sender: TObject);
118115begin
119116
120117end;
121118```
122119
123120Between *begin* and *end* we must enter the instructions needed to display the data.... obviously that will be something to do with SQLQuery1..
124121
125122The 'SQL' property of SQLQuery1 can only be changed, if SQLQuery1 is not active. That's why we close the component first:
126123
127124``` pascal
128125SQLQuery1.Close;
129126```
130127
131128Then we assign our SQL instruction to the 'SQL' property, overwriting any previous SQL commands:
132129
133130``` pascal
134131SQLQuery1.SQL.Text := 'select * from CUSTOMER';
135132```
136133
137134Now we need to establish the connection to the database, activate the transaction and open the query:
138135
139136``` pascal
140137DBConnection.Connected := True;
141138SQLTransaction1.Active := True;
142139SQLQuery1.Open;
143140```
144141
145142You can omit the first two instructions, because they are done automatically by the third instruction. If you compile the project at this point, you could already see the data from the 'CUSTOMER' table.
146143
147144However, a serious application must make sure that all open database connections are properly closed when not needed anymore. Otherwise the secondary effects would not be foreseeable. So, we use the OnClose event of our form (create it with a double click in the object inspector):
148145
149146``` pascal
150147procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction);
151148begin
152149
153150end;
154151```
155152
156153To close the connection we use the reverse order compared to our opening code:
157154
158155``` pascal
159156SQLQuery1.Close;
160157SQLTransaction1.Active := False;
161158DBConnection.Connected := False;
162159```
163160
164161If you set DBConnection.Connected to False, the Transaction and the Query is automatically closed and you can omit closing them manually.
165162
166163## Summary
167164
168165Up to now we have learned how to connect to a database using the SQLdb package and how to display the contents of a table on the screen. If you want to add more functionality such as editing, please continue with [[SQLdb Tutorial2]]
169166
170167If you followed the previous steps, then your code should look like:
171168
172169``` pascal
173170unit Unit1;
174171
175172{$mode objfpc}{$H+}
176173
177174interface
178175
179176uses
180177 Classes, SysUtils, IBConnection, sqldb, db, FileUtil, Forms, Controls,
181178 Graphics, Dialogs, DBGrids, StdCtrls;
182179
183180type
184181
185182 { TForm1 }
186183
187184 TForm1 = class(TForm)
188185 Button1: TButton;
189186 Datasource1: TDatasource;
190187 DBGrid1: TDBGrid;
191188 DBConnection: TIBConnection;
192189 SQLQuery1: TSQLQuery;
193190 SQLTransaction1: TSQLTransaction;
194191 procedure Button1Click(Sender: TObject);
195192 procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
196193 private
197194 { private declarations }
198195 public
199196 { public declarations }
200197 end;
201198
202199var
203200 Form1: TForm1;
204201
205202implementation
206203
207204{$R *.lfm}
208205
209206{ TForm1 }
210207
211208procedure TForm1.Button1Click(Sender: TObject);
212209begin
213210 SQLQuery1.Close;
214211 SQLQuery1.SQL.Text:= 'select * from CUSTOMER';
215212 DBConnection.Connected:= True;
216213 SQLTransaction1.Active:= True;
217214 SQLQuery1.Open;
218215end;
219216
220217procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction);
221218begin
222219 SQLQuery1.Close;
223220 SQLTransaction1.Active:= False;
224221 DBConnection.Connected:= False;
225222end;
226223
227224end.
228225```
229226
230227## See also
231228
232229- [[SQLdb Tutorial0]]: Instructions for setting up sample tables/sample data for the tutorial series.
233230- [[SQLdb Tutorial2]]: Second part of the DB tutorial series, showing editing, inserting etc.
234231- [[SQLdb Tutorial3]]: Third part of the DB tutorial series, showing how to program for multiple databases and use a login form
235232- [[SQLdb Tutorial4]]: Fourth part of the DB tutorial series, showing how to use data modules
236233- [[Lazarus Database Overview]]: Information about the databases that Lazarus supports. Links to database-specific notes.
237234- [[SQLdb Package]]: information about the SQLdb package
238235- [[SQLdb Programming Reference]]: an overview of the interaction of the SQLdb database components
239236- [[SqlDBHowto]]: information about using the SQLdb package
240237- [[Working With TSQLQuery]]: information about TSQLQuery
241238
242239---
243240*From the Free Pascal wiki, page "SQLdb Tutorial1", as it stood on 2022-11-01 after a change by Kj14, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*

Back to history