Sign in Join
Wiki copytemporary

MySQLDatabases: what changed

Revision 3 to 4. Removed lines have a minus sign; added lines have a plus sign.

OldNewLine
1+---
2+[[Portal:Databases|**Databases portal**]]
3+References: · [[Databases|General info]] · [[Database libraries|Libraries]] · [[Database field type|Field types]] · [[Data Controls tab|Controls]] · [[Lazarus DB Faq|FAQ]] · [[SqlDBHowto|SQL how-to]] · [[Working With TSQLQuery]] · [[How to write in-memory database applications in Lazarus/FPC|In-memory database applications]] · Tutorials/practical articles: · [[Lazarus Database Overview|Overview]] · [[SQLdb Tutorial0|0 - Database set-up]] · [[SQLdb Tutorial1|1 - Getting started]] · [[SQLdb Tutorial2|2 - Editing]] · [[SQLdb Tutorial3|3 - Queries]] · [[SQLdb Tutorial4|4 - Data modules]] · [[SQLdb Programming Reference]] · Databases · [[Advantage Database Server|Advantage]] \- MySQL \- [[mssqlconn|MSSQL]] \- [[postgres|Postgres]] \- [[Firebird|Interbase]] \- [[Firebird]] \- [[Oracle]] \- [[ODBCConn|ODBC]] \- [[TParadox|Paradox]] \- [[SQLite]] \- [[Lazarus Tdbf Tutorial|dBASE]] \- [[MS Access]] \- [[Zeos tutorial|Zeos]]
4+
5+
16## Introduction
27
3-This page will explain how to connect to a [[mysql|MySQL]] server using visual components.
8+This page will explain how to connect to a [[mysql|MySQL]] server using visual components.
49
5-> **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
10+![Light bulb](https://upload.wikimedia.org/wikipedia/commons/d/d8/Nuvola_apps_ktip.png) **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
611
7-Note: see also these tutorials that teach data-bound controls, parameterized queries, database independent programming etc:
12+Note: see also these tutorials that teach data-bound controls, parameterized queries, database independent programming etc:
813
9-- [[SQLdb Tutorial1]]
10-- [[SQLdb Tutorial2]]
11-- [[SQLdb Tutorial3]]
14+ * [[SQLdb Tutorial1]]
15+ * [[SQLdb Tutorial2]]
16+ * [[SQLdb Tutorial3]]
1217
13-They are written for all databases that support sqldb, including MySQL.
18+They are written for all databases that support sqldb, including MySQL.
1419
15-If needed, see also [[mysql|mysql#SQLDB_tutorials_and_example_code]] for yet more tutorials (that are also written a long time ago.
20+If needed, see also [[mysql|mysql#SQLDB_tutorials_and_example_code]] for yet more tutorials (that are also written a long time ago.
1621
1722## Available Components
1823
1924### SQLdb Components
2025
21-In any even vaguely recent version of Lazarus, the SQLDB components are installed by default.
26+In any even vaguely recent version of Lazarus, the SQLDB components are installed by default.
2227
23-![](/wiki-images/c/c5/Sqldbcomponents.png%E2%80%8E)
28+[![sqldbcomponents.png](/wiki-images/8/82/sqldbcomponents.png)](</File:sqldbcomponents.png>)
2429
25-On the SQLDB tab you will find:
30+On the SQLDB tab you will find:
2631
27-- 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.
28-- [[TSQLQuery]]
32+ * 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.
33+ * [[TSQLQuery]]
2934
30-If the SQLDB tab is missing, have a look at [[Install Packages]] for an "Install Howto".
35+If the SQLDB tab is missing, have a look at [[Install Packages]] for an "Install Howto".
3136
3237## Explanation of the used components
3338
3439### TMySQLConnection
3540
36-The 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.
41+The 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.
3742
38-> **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.
43+![Light bulb](https://upload.wikimedia.org/wikipedia/commons/d/d8/Nuvola_apps_ktip.png) **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.
3944
40-You 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.
45+You 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.
4146
42-In all cases put a copy of libmysql.dll *and any other required files/dlls*
47+In all cases put a copy of libmysql.dll _and any other required files/dlls_
4348
44-- in your Lazarus directory and the same directory as your project files or
45-- 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.
49+ * in your Lazarus directory and the same directory as your project files or
50+ * 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.
4651
4752### TSQLTransaction
4853
49-A [[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.
54+A [[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.
5055
5156### TSQLQuery
5257
53-[[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.
58+[[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.
5459
5560### TDataSource
5661
57-A [[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.
62+A [[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.
5863
5964### TDBGrid
6065
61-A [[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.
66+A [[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.
6267
6368## Our program
6469
6570### The basics
6671
67-We 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.
72+We 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](</User:Kirkpatc> "User:Kirkpatc").
6873
6974### The main form
7075
71-We 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.
72-
73-```text
74-image:Trymysql.png
76+We 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.
7577```
76-
77-From 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:
78+[![Trymysql.png](/wiki-images/2/28/Trymysql.png)](</File:Trymysql.png>)
79+```
7880
79-| | | |
80-|------------------|--------------|------------------|
81-| **Component** | **Property** | **Value** |
82-| MySQLConnection1 | Transaction | SQLTransaction1 |
83-| SQLTransaction1 | Database | MySQLConnection1 |
84-| SQLQuery1 | Transaction | SQLTransaction1 |
85-| SQLQuery1 | Database | MySQLConnection1 |
81+From the SQLdb-tab place a [[TMySQL56Connection]] [![tmysql56connection.png](/wiki-images/7/76/tmysql56connection.png)](</File:tmysql56connection.png>) (or other mysql-client version) a [[TSQLTransaction]] [![tsqltransaction.png](/wiki-images/f/fd/tsqltransaction.png)](</File:tsqltransaction.png>) and a [[TSQLQuery]] [![tsqlquery.png](/wiki-images/b/be/tsqlquery.png)](</File: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:
8682
87-The 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.
83+**Component** | **Property** | **Value**
84+---|---|---
85+MySQLConnection1 | Transaction | SQLTransaction1
86+SQLTransaction1 | Database | MySQLConnection1
87+SQLQuery1 | Transaction | SQLTransaction1
88+SQLQuery1 | Database | MySQLConnection1
89+
90+The 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.
8891
89-As said earlier: Make sure you are using the correct Connection component for your version of MySQL server.
92+As said earlier: Make sure you are using the correct Connection component for your version of MySQL server.
9093
9194### The code
9295
93-As 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." :)
94-
95-Before 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
96+As 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." :)
9697
97-```text
98+Before 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
99+```
98100try ... finally
99101```
100102
101-or
102-
103-```text
103+or
104+```
104105try ... except
105106```
106107
107-constructions.
108+constructions.
108109
109110#### Connect to a server
110111
111-The 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.
112-
113-``` pascal
112+The 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.
113+```
114114procedure TFormTryMySQL.ConnectButtonClick(Sender: TObject);
115-begin
116- // Check if we have an active connection. If so, let's close it.
117- if MySQLConnection1.Connected then CloseConnection(Sender);
118- // Set the connection parameters.
119- MySQLConnection1.HostName := HostEdit.Text;
120- MySQLConnection1.UserName := UserEdit.Text;
121- MySQLConnection1.Password := PasswdEdit.Text;
122- MySQLConnection1.DatabaseName := 'mysql'; // MySQL is allways there!
123- ShowString('Opening a connection to server: ' + HostEdit.Text);
124- MySQLConnection1.Open;
125- // First lets get a list of available databases.
126- if MySQLConnection1.Connected then begin
127- ShowString('Connected to server: ' + HostEdit.Text);
128- ShowString('Retrieving list of available databases.');
129- SQLQuery1.SQL.Text := 'show databases';
130- SQLQuery1.Open;
131- while not SQLQuery1.EOF do begin
132- DatabaseComboBox.Items.Add(SQLQuery1.Fields[0].AsString);
133- SQLQuery1.Next;
115+ begin
116+ // Check if we have an active connection. If so, let's close it.
117+ if MySQLConnection1.Connected then CloseConnection(Sender);
118+ // Set the connection parameters.
119+ MySQLConnection1.HostName := HostEdit.Text;
120+ MySQLConnection1.UserName := UserEdit.Text;
121+ MySQLConnection1.Password := PasswdEdit.Text;
122+ MySQLConnection1.DatabaseName := 'mysql'; // MySQL is allways there!
123+ ShowString('Opening a connection to server: ' + HostEdit.Text);
124+ MySQLConnection1.Open;
125+ // First lets get a list of available databases.
126+ if MySQLConnection1.Connected then begin
127+ ShowString('Connected to server: ' + HostEdit.Text);
128+ ShowString('Retrieving list of available databases.');
129+ SQLQuery1.SQL.Text := 'show databases';
130+ SQLQuery1.Open;
131+ while not SQLQuery1.EOF do begin
132+ DatabaseComboBox.Items.Add(SQLQuery1.Fields[0].AsString);
133+ SQLQuery1.Next;
134+ end;
135+ SQLQuery1.Close;
136+ ShowString('List of databases received!');
137+ end;
134138 end;
135- SQLQuery1.Close;
136- ShowString('List of databases received!');
137- end;
138-end;
139139```
140140
141-The 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.
142-
143-
144-*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.*
141+The 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.
145142
146-With the parameters set, we can connect to the server. This is done by calling
143+_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._
147144
148-``` pascal
145+With the parameters set, we can connect to the server. This is done by calling
146+```
149147MySQLConnection1.Open;
150148```
151149
152-In 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
153-
154-``` pascal
150+In 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
151+```
155152SQLQuery1.Open;
156153```
157154
158-On MySQL5 set this to correct error with SQL syntax:
159-
160-``` pascal
155+On MySQL5 set this to correct error with SQL syntax:
156+```
161157SQLQuery1.ParseSQL := False;
162-SQLQuery1.ReadOnly := True;
158+ SQLQuery1.ReadOnly := True;
163159```
164160
165-The result set of a SQLQuery can be examined through the fields property. As you can see we iterate through the records by calling
166-
167-``` pascal
161+The result set of a SQLQuery can be examined through the fields property. As you can see we iterate through the records by calling
162+```
168163SQLQuery1.Next;
169164```
170165
171-When we have added all available databases to our combobox, we close the SQLQuery again.
166+When we have added all available databases to our combobox, we close the SQLQuery again.
172167
173168#### Selecting a database
174169
175-If 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.
176-
177-``` pascal
170+If 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.
171+```
178172procedure TFormTryMySQL.SelectDBButtonClick(Sender: TObject);
179-begin
180- // A database has been selected so lets get the tables in it.
181- CloseConnection(Sender);
182- if DatabaseComboBox.ItemIndex <> -1 then begin
183- with DatabaseComboBox do
184- MySQLConnection1.DatabaseName := Items[ItemIndex];
185- ShowString('Retreiving list of tables');
186- SQLQuery1.SQL.Text := 'show tables';
187- SQLQuery1.Open;
188- while not SQLQuery1.EOF do begin
189- TableComboBox.Items.Add(SQLQuery1.Fields[0].AsString);
190- SQLQuery1.Next;
173+ begin
174+ // A database has been selected so lets get the tables in it.
175+ CloseConnection(Sender);
176+ if DatabaseComboBox.ItemIndex <> -1 then begin
177+ with DatabaseComboBox do
178+ MySQLConnection1.DatabaseName := Items[ItemIndex];
179+ ShowString('Retreiving list of tables');
180+ SQLQuery1.SQL.Text := 'show tables';
181+ SQLQuery1.Open;
182+ while not SQLQuery1.EOF do begin
183+ TableComboBox.Items.Add(SQLQuery1.Fields[0].AsString);
184+ SQLQuery1.Next;
185+ end;
186+ SQLQuery1.Close;
187+ ShowString('List of tables received');
188+ end;
189+ OpenQueryButton.Enabled := True;
191190 end;
192- SQLQuery1.Close;
193- ShowString('List of tables received');
194- end;
195- OpenQueryButton.Enabled := True;
196-end;
197191```
198192
199-MySQL 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.
193+MySQL 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.
200194
201195#### Fields in a table
202196
203-In 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.
204-
205-``` pascal
197+In 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.
198+```
206199procedure TFormTryMySQL.TableComboBoxChange(Sender: TObject);
207-begin
208- FieldListBox.Clear;
209- SQLQuery1.SQL.Text := 'show columns from ' + TableComboBox.Text;
210- SQLQuery1.Open;
211- while not SQLQuery1.EOF do begin
212- FieldListBox.Items.Add(SQLQuery1.Fields[0].AsString);
213- SQLQuery1.Next;
214- end;
215- SQLQuery1.Close;
216-end;
200+ begin
201+ FieldListBox.Clear;
202+ SQLQuery1.SQL.Text := 'show columns from ' + TableComboBox.Text;
203+ SQLQuery1.Open;
204+ while not SQLQuery1.EOF do begin
205+ FieldListBox.Items.Add(SQLQuery1.Fields[0].AsString);
206+ SQLQuery1.Next;
207+ end;
208+ SQLQuery1.Close;
209+ end;
217210```
218211
219-As 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.
212+As 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.
220213
221214#### Showing the data
222215
223-Well 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:
224-
225-``` pascal
216+Well 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:
217+```
226218procedure TFormTryMySQL.OpenQueryButtonClick(Sender: TObject);
227-begin
228- ShowQueryForm := TShowQueryForm.Create(self);
229- ShowQueryForm.Datasource1.DataSet := SQLQuery1;
230- SQLQuery1.SQL.Text := CommandEdit.Text;
231- SQLQuery1.Open;
232- ShowQueryForm.ShowModal;
233- ShowQueryForm.Free;
234- SQLQuery1.Close;
235-end;
219+ begin
220+ ShowQueryForm := TShowQueryForm.Create(self);
221+ ShowQueryForm.Datasource1.DataSet := SQLQuery1;
222+ SQLQuery1.SQL.Text := CommandEdit.Text;
223+ SQLQuery1.Open;
224+ ShowQueryForm.ShowModal;
225+ ShowQueryForm.Free;
226+ SQLQuery1.Close;
227+ end;
236228```
237229
238-The ShowQueryForm looks like this:
239-
240-![](/wiki-images/4/47/Mysqlshow.png)
241-
242-and contains a
230+The ShowQueryForm looks like this:
243231
244-| | | |
245-|----|----|----|
246-| [[TPanel]] | Align | alBottom |
247-| [[TDataSource]] | | |
248-| [[TDBGrid]] | Align | alClient |
249-| | DataSource | DataSource1 |
250-| [[TButton]] | Caption | Close |
232+[![Mysqlshow.png](/wiki-images/4/47/Mysqlshow.png)](</File:Mysqlshow.png>)
251233
252-The 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.
234+and contains a
253235
254-The 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:
236+[[TPanel]] | Align | alBottom
237+---|---|---
238+[[TDataSource]] | |
239+[[TDBGrid]] | Align | alClient
240+| DataSource | DataSource1
241+[[TButton]] | Caption | Close
242+
243+The 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.
255244
256-Add a Button at the bottom of the ShowQuery Form named AddButton and with Caption 'Add'. Create a method for AddButtonClick like this:
245+The 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:
257246
258-``` pascal
247+Add a Button at the bottom of the ShowQuery Form named AddButton and with Caption 'Add'. Create a method for AddButtonClick like this:
248+```
259249procedure TShowQueryForm.AddButtonClick(Sender: TObject);
260-begin
261- DataSource1.DataSet.Append;
262-end;
250+ begin
251+ DataSource1.DataSet.Append;
252+ end;
263253```
264254
265-Change the code for OpenQueryButtonClick to allow for updates to the database when we finish with the Query Form.
266-
267-``` pascal
255+Change the code for OpenQueryButtonClick to allow for updates to the database when we finish with the Query Form.
256+```
268257procedure TFormTryMySQL.OpenQueryButtonClick(Sender: TObject);
269-begin
270- ShowQueryForm := TShowQueryForm.Create(nil);
271- try
272- ShowQueryForm.DataSource1.DataSet := SQLQuery1;
273- // We will write in the database, so let's set ReadOnly to false,
274- // and for that we need to set ParseSQL true
275- SQLQuery1.ParseSQL:=true;
276- SQLQuery1.ReadOnly:=false;
277- SQLQuery1.SQL.Text := CommandEdit.Text;
278- SQLQuery1.Open;
279- ShowQueryForm.ShowModal;
280- finally
281- // set up update mode, and update database
282- SQLQuery1.UpdateMode:=upWhereChanged;
283- SQLQuery1.ApplyUpdates;
284- SQLTransaction1.Commit;
285- ShowQueryForm.Free;
286- SQLQuery1.Close;
287- // set read-only and parsesql back to default
288- SQLQuery1.ParseSQL:=false;
289- SQLQuery1.ReadOnly:=true;
290- end;
291-end;
258+ begin
259+ ShowQueryForm := TShowQueryForm.Create(nil);
260+ try
261+ ShowQueryForm.DataSource1.DataSet := SQLQuery1;
262+ // We will write in the database, so let's set ReadOnly to false,
263+ // and for that we need to set ParseSQL true
264+ SQLQuery1.ParseSQL:=true;
265+ SQLQuery1.ReadOnly:=false;
266+ SQLQuery1.SQL.Text := CommandEdit.Text;
267+ SQLQuery1.Open;
268+ ShowQueryForm.ShowModal;
269+ finally
270+ // set up update mode, and update database
271+ SQLQuery1.UpdateMode:=upWhereChanged;
272+ SQLQuery1.ApplyUpdates;
273+ SQLTransaction1.Commit;
274+ ShowQueryForm.Free;
275+ SQLQuery1.Close;
276+ // set read-only and parsesql back to default
277+ SQLQuery1.ParseSQL:=false;
278+ SQLQuery1.ReadOnly:=true;
279+ end;
280+ end;
292281```
293282
294-We 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.
295-
296-If 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):
283+We 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.
297284
298-``` sql
285+If 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):
286+```
299287ALTER TABLE TRESTRIG
300-ADD COLUMN AUTOID INT
301-PRIMARY KEY AUTO_INCREMENT;
288+ ADD COLUMN AUTOID INT
289+ PRIMARY KEY AUTO_INCREMENT;
302290```
303291
304-and then you will find that the Delete button on the navigator works.
292+and then you will find that the Delete button on the navigator works.
305293
306294## Sources
307295
308-The 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)
296+The 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>)
309297
310298## See also
311299
312-- [[mysql]]
300+ * [[mysql]]
313301
314302---
315-*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).*
303+*From the Free Pascal wiki, page "MySQLDatabases", as the Internet Archive kept it on 2024-09-06, last changed on 2020-02-21. 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