Sign in Join
Wiki copytemporary

MySQLDatabases: what changed

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

OldNewLine
11## Introduction
22
33This page will explain how to connect to a [[mysql|MySQL]] server using visual components.
44
55> **Note:** This page has been written a long time ago and may be out of date. Also, most of the concepts described here are not MySQL specific but apply to all SQLDB databases. Therefore, following the SQLdb Tutorial series mentioned below may be easier
66
77Note: see also these tutorials that teach data-bound controls, parameterized queries, database independent programming etc:
88
99- [[SQLdb Tutorial1]]
1010- [[SQLdb Tutorial2]]
1111- [[SQLdb Tutorial3]]
1212
1313They are written for all databases that support sqldb, including MySQL.
1414
1515If needed, see also [[mysql|mysql#SQLDB_tutorials_and_example_code]] for yet more tutorials (that are also written a long time ago.
1616
1717## Available Components
1818
1919### SQLdb Components
2020
2121In any even vaguely recent version of Lazarus, the SQLDB components are installed by default.
2222
23-<figure>
24-<img src="sqldbcomponents.png‎" title="sqldbcomponents.png‎" />
25-<figcaption>sqldbcomponents.png‎</figcaption>
26-</figure>
23+![](/wiki-images/c/c5/Sqldbcomponents.png%E2%80%8E)
2724
2825On the SQLDB tab you will find:
2926
3027- Various connectors, including [[TMySQL40Connection]]..[[TMySQL56Connection]] (or perhaps even newer versions) and the most versatile of all [[TSQLConnector]] that may load any of the mysql/oracle/postgres/mssql/interbase/firebird/odbc drivers.
3128- [[TSQLQuery]]
3229
3330If the SQLDB tab is missing, have a look at [[Install Packages]] for an "Install Howto".
3431
3532## Explanation of the used components
3633
3734### TMySQLConnection
3835
3936The TMySQLConnection is used to store parameters to connect to the database server. It enables you to set the host to connect to, and the userid and password to use in the connection. Another property of the TMySQLConnection is used to indicate the database you want to use. The 'LoginPrompt' is not functional yet, so make sure that next to the HostName and DatabaseName the UserName and Password properties have values as well before you try to open the connection. Be sure to use a TSQLTransaction as well and connect it to your MySQLConnection by setting the Transaction property, or you will not be able to open a SQLQuery.
4037
4138> **Note:** As indicated above, there are various MySQLConnection components that differ in version number. The version number **must** match the version number of the client library you use to connect to your server. So if you are running a MySQL 5.1 server but use a MySQL 5.0 client, use the TMySQL50Connection.
4239
4340You should check MySQL documentation to make sure the combination between client version and server version is supported - e.g. you may well have problems connecting to a 4.0 server using a 5.x client.
4441
4542In all cases put a copy of libmysql.dll *and any other required files/dlls*
4643
4744- in your Lazarus directory and the same directory as your project files or
4845- in the Windows system directory (if you don't want to keep copying files). Note that on 64 bit Windows you have to put the 32 bit library in SysWOW64, while 64 bit libraries go into System32.
4946
5047### TSQLTransaction
5148
5249A [[TSQLTransaction]] is needed for some internal housekeeping. A SQLTransaction is automatically activated when you open a dataset using it. Closing a connection also deactivates the related transaction and closes all datasets using it.
5350
5451### TSQLQuery
5552
5653[[TSQLQuery]] is used to execute SQLstatements on the server. You can retrieve data by setting the SQL to some SELECT statement and call the Open method. Or you can manipulate data by issuing some an INSERT, DELETE or UPDATE statement. In the latter case you should not use the Open method but the ExecSQL method.
5754
5855### TDataSource
5956
6057A [[TDataSource]] provides the connection between the visible data aware components like DBEdit, DBGrid and a dataset. It makes the data available for the data aware components to display. A datasource can only be connected to a single dataset at a time but there can be several data aware components connected.
6158
6259### TDBGrid
6360
6461A [[TDBGrid]] can be used to present the data retrieved by a Dataset. The DBGrid needs a datasource to connect to a dataset. When the dataset is opened, the DBgrid will automatically be populated with the data.
6562
6663## Our program
6764
6865### The basics
6966
7067We will try to make a program based on the one made [[Lazarus Database Tutorial/nl|here (in Dutch)]] which is based on the [[Lazarus Database Tutorial|original (in English)]] by Chris.
7168
7269### The main form
7370
7471We will use the same main screen and build all functionality from scratch :) As you will see there is a lot less to take care of, because the components really take away all the hard stuff! So lets start by making a screen that looks like this.
7572
7673![`Trymysql.png`](/wiki-images/2/28/Trymysql.png)
7774
7875From the SQLdb-tab place a [[TMySQL56Connection]] ![](/wiki-images/9/97/Tmysql56connection.png) (or other mysql-client version) a [[TSQLTransaction]] ![](/wiki-images/b/bd/Tsqltransaction.png) and a [[TSQLQuery]] ![](/wiki-images/b/bb/Tsqlquery.png) on this form. Don't change the default names given to this components. Except for the connection component. To make this article the same for all versions of MySQL, name your TMySQL##Connection component: `MySQLConnection1`. We have to link these components together so they can do their job. So the following properties have to be set:
7976
8077| | | |
8178|------------------|--------------|------------------|
8279| **Component** | **Property** | **Value** |
8380| MySQLConnection1 | Transaction | SQLTransaction1 |
8481| SQLTransaction1 | Database | MySQLConnection1 |
8582| SQLQuery1 | Transaction | SQLTransaction1 |
8683| SQLQuery1 | Database | MySQLConnection1 |
8784
8885The Transaction-property of SQLQuery1 will automatically be set if you have set the Transaction property of MySQLConnection1 first. When you set this, you will notice that SQLTransaction1.Database has been set to MySQLConnection1.
8986
9087As said earlier: Make sure you are using the correct Connection component for your version of MySQL server.
9188
9289### The code
9390
9491As you can see in the screen dump the only buttons available on start of the program are "Connect to server" and "Exit". For the other buttons to work we need more information so these are disabled. We could decide to disable "Connect to Server" as well until the information for the host, username and password has been given. I decided against this because our user might think: "Nothing seems possible, so let's hit exit." :)
9592
9693Before I start giving you any code I would like to stress that there should be more exception handling in the code. Critical sections should be placed in
9794
9895`try ... finally`
9996
10097or
10198
10299`try ... except`
103100
104101constructions.
105102
106103#### Connect to a server
107104
108105The first thing we have to do is get connected to our server. As when connecting we don't know what databases are available on the server we will ask for a list of databases on connecting. However there is one catch, to make the connection we have to enter a valid DatabaseName in the properties of the MySQLConnection. You will see in the code that I am using the "mysql" database. This database is used by mysql for some housekeeping so it will always be there.
109106
110107``` pascal
111108procedure TFormTryMySQL.ConnectButtonClick(Sender: TObject);
112109begin
113110 // Check if we have an active connection. If so, let's close it.
114111 if MySQLConnection1.Connected then CloseConnection(Sender);
115112 // Set the connection parameters.
116113 MySQLConnection1.HostName := HostEdit.Text;
117114 MySQLConnection1.UserName := UserEdit.Text;
118115 MySQLConnection1.Password := PasswdEdit.Text;
119116 MySQLConnection1.DatabaseName := 'mysql'; // MySQL is allways there!
120117 ShowString('Opening a connection to server: ' + HostEdit.Text);
121118 MySQLConnection1.Open;
122119 // First lets get a list of available databases.
123120 if MySQLConnection1.Connected then begin
124121 ShowString('Connected to server: ' + HostEdit.Text);
125122 ShowString('Retrieving list of available databases.');
126123 SQLQuery1.SQL.Text := 'show databases';
127124 SQLQuery1.Open;
128125 while not SQLQuery1.EOF do begin
129126 DatabaseComboBox.Items.Add(SQLQuery1.Fields[0].AsString);
130127 SQLQuery1.Next;
131128 end;
132129 SQLQuery1.Close;
133130 ShowString('List of databases received!');
134131 end;
135132end;
136133```
137134
138135The first thing we do is check to see if we are connected to a server, if we are then we call a private method "CloseConnection". In this method some more housekeeping is done. like disabling buttons and clearing comboboxes and listboxes. Then we set the necessary parameters to connect to server.
139136
140137
141138*Throughout our program you may see calls to ShowString. This method adds a line to the memo on our form which acts like a kind of log.*
142139
143140With the parameters set, we can connect to the server. This is done by calling
144141
145142``` pascal
146143MySQLConnection1.Open;
147144```
148145
149146In a proper application one would place this in an exception handling construct to present a friendly message to the user if the connection failed. When we are connected we want to get a list of databases from the server. To get data from the server a TSQLQuery is used. The SQL property is used to store the SQL-statement send to the server. MySQL knows the "SHOW DATABASES" command to get the list of databases. So after we have set the SQL-text, we call
150147
151148``` pascal
152149SQLQuery1.Open;
153150```
154151
155152On MySQL5 set this to correct error with SQL syntax:
156153
157154``` pascal
158155SQLQuery1.ParseSQL := False;
159156SQLQuery1.ReadOnly := True;
160157```
161158
162159The result set of a SQLQuery can be examined through the fields property. As you can see we iterate through the records by calling
163160
164161``` pascal
165162SQLQuery1.Next;
166163```
167164
168165When we have added all available databases to our combobox, we close the SQLQuery again.
169166
170167#### Selecting a database
171168
172169If the user selects a database in the DatabaseComboBox we enable the "Select Database" button. In the OnClick event of this button we set the DatabaseName of MySQLConnection1, and request a list of tables. The last statement of this procedure enables the "Open Query" Button, so the user can enter a query in the "Command" Editbox and have it send to the server.
173170
174171``` pascal
175172procedure TFormTryMySQL.SelectDBButtonClick(Sender: TObject);
176173begin
177174 // A database has been selected so lets get the tables in it.
178175 CloseConnection(Sender);
179176 if DatabaseComboBox.ItemIndex <> -1 then begin
180177 with DatabaseComboBox do
181178 MySQLConnection1.DatabaseName := Items[ItemIndex];
182179 ShowString('Retreiving list of tables');
183180 SQLQuery1.SQL.Text := 'show tables';
184181 SQLQuery1.Open;
185182 while not SQLQuery1.EOF do begin
186183 TableComboBox.Items.Add(SQLQuery1.Fields[0].AsString);
187184 SQLQuery1.Next;
188185 end;
189186 SQLQuery1.Close;
190187 ShowString('List of tables received');
191188 end;
192189 OpenQueryButton.Enabled := True;
193190end;
194191```
195192
196193MySQL has a special command to get a list of tables, comparable to getting the list of databases, "show tables". The result of this query is handled in the same way as the list of databases and all the tables are added to the TableComboBox. You might wonder why we do not open the connection again before opening the query? Well, this is done automatically (if necessary) when we activate the SQLQuery.
197194
198195#### Fields in a table
199196
200197In MySQL you can again use a form of "SHOW" to get the fields in a table. In this case "SHOW COLUMNS FROM \<tablename\>". If the user picks a table from the TableComboBox the OnChangeEvent of this ComboBox is triggered which fills the FieldListbox.
201198
202199``` pascal
203200procedure TFormTryMySQL.TableComboBoxChange(Sender: TObject);
204201begin
205202 FieldListBox.Clear;
206203 SQLQuery1.SQL.Text := 'show columns from ' + TableComboBox.Text;
207204 SQLQuery1.Open;
208205 while not SQLQuery1.EOF do begin
209206 FieldListBox.Items.Add(SQLQuery1.Fields[0].AsString);
210207 SQLQuery1.Next;
211208 end;
212209 SQLQuery1.Close;
213210end;
214211```
215212
216213As well as the names of the fields, the result set contains information on the type of field, if the field is a key, if nulls are allowed and some more.
217214
218215#### Showing the data
219216
220217Well as we said we would use components to get connected to the database, lets use some components to show the data as well. We will use a second form to show a grid with the data requested by the user. This form will be shown when the user typed a SQL command in the "Command" editbox and afterwards clicks the "Open Query" button. This is the OnClick event:
221218
222219``` pascal
223220procedure TFormTryMySQL.OpenQueryButtonClick(Sender: TObject);
224221begin
225222 ShowQueryForm := TShowQueryForm.Create(self);
226223 ShowQueryForm.Datasource1.DataSet := SQLQuery1;
227224 SQLQuery1.SQL.Text := CommandEdit.Text;
228225 SQLQuery1.Open;
229226 ShowQueryForm.ShowModal;
230227 ShowQueryForm.Free;
231228 SQLQuery1.Close;
232229end;
233230```
234231
235232The ShowQueryForm looks like this:
236233
237-<center>
238-
239-<figure>
240-<img src="Mysqlshow.png" title="Mysqlshow.png" />
241-<figcaption>Mysqlshow.png</figcaption>
242-</figure>
243-
244-</center>
234+![](/wiki-images/4/47/Mysqlshow.png)
245235
246236and contains a
247237
248238| | | |
249239|----|----|----|
250240| [[TPanel]] | Align | alBottom |
251241| [[TDataSource]] | | |
252242| [[TDBGrid]] | Align | alClient |
253243| | DataSource | DataSource1 |
254244| [[TButton]] | Caption | Close |
255245
256246The button is placed on the panel. What happens in the "Open Query" OnClick is this. First we create an instance of TShowQueryForm. Secondly we set the DataSet property of the DataSource to our SQLQuery1. Then we set the SQLQuery SQL command to what the user entered in the "Command" editbox and open it. Then the ShowQueryForm is shown modally, this means that it will have the focus of our application until it is closed. When it is closed, we "free" it and close SQLQuery1 again.
257247
258248The Form can be further enhanced by inserting a method for modifying the content of the [[TDataSet]] and ultimately the DataBase. A full version can be downloaded from <http://digitus.itk.ppke.hu/~janma/lazarus/MySql5Test.tar.gz> (with thanks to Arwen and JZombi from the Lazarus MySQL Forum) but the relevant details are as follows:
259249
260250Add a Button at the bottom of the ShowQuery Form named AddButton and with Caption 'Add'. Create a method for AddButtonClick like this:
261251
262252``` pascal
263253procedure TShowQueryForm.AddButtonClick(Sender: TObject);
264254begin
265255 DataSource1.DataSet.Append;
266256end;
267257```
268258
269259Change the code for OpenQueryButtonClick to allow for updates to the database when we finish with the Query Form.
270260
271261``` pascal
272262procedure TFormTryMySQL.OpenQueryButtonClick(Sender: TObject);
273263begin
274264 ShowQueryForm := TShowQueryForm.Create(nil);
275265 try
276266 ShowQueryForm.DataSource1.DataSet := SQLQuery1;
277267 // We will write in the database, so let's set ReadOnly to false,
278268 // and for that we need to set ParseSQL true
279269 SQLQuery1.ParseSQL:=true;
280270 SQLQuery1.ReadOnly:=false;
281271 SQLQuery1.SQL.Text := CommandEdit.Text;
282272 SQLQuery1.Open;
283273 ShowQueryForm.ShowModal;
284274 finally
285275 // set up update mode, and update database
286276 SQLQuery1.UpdateMode:=upWhereChanged;
287277 SQLQuery1.ApplyUpdates;
288278 SQLTransaction1.Commit;
289279 ShowQueryForm.Free;
290280 SQLQuery1.Close;
291281 // set read-only and parsesql back to default
292282 SQLQuery1.ParseSQL:=false;
293283 SQLQuery1.ReadOnly:=true;
294284 end;
295285end;
296286```
297287
298288We can now add records to the Database. If we add a TDBNavigator to the ShowQuery Form we can move around the Data Grid more easily, and edit records; the database gets updated with our changes each time we close the ShowQuery Form, and we can test this by opening it up again to inspect the database.
299289
300290If you want to be able to DELETE or otherwise modify records on the original database (ie make sure changes you make to the local dataset get committed back to the database) then you need to have one column in your database table that is a primary key autoincremented, as the 'delete' method requires to be able to generate a 'where' clause when writing instructions back to the database, to identify the records selected for deletion. So use the following code in your MySQL client (it can all be typed on one line, but line breaks have been added for clarity):
301291
302292``` sql
303293ALTER TABLE TRESTRIG
304294ADD COLUMN AUTOID INT
305295PRIMARY KEY AUTO_INCREMENT;
306296```
307297
308298and then you will find that the Delete button on the navigator works.
309299
310300## Sources
311301
312302The sources for this project can be downloaded [here](http://prdownloads.sourceforge.net/lazarus-ccr/mysql_demo_20050408.tar.gz?download) For more demo projects see [sourceforge](http://sourceforge.net/project/showfiles.php?group_id=92177&package_id=148359)
313303
314304## See also
315305
316306- [[mysql]]
317307
318308---
319309*From the Free Pascal wiki, page "MySQLDatabases", as it stood on 2020-02-20 after a change by Trev, 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