Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube. There are several Serial Communication (COM port) options available for Lazarus, but I would first suggest giving Synaser another try. I'm currently using Lazarus 1.2.4 with Synaser from Synapse v40 and even latest trunk revision without any problems. Lucas has also just released version 12 of his Synaser serial port communications suite that also runs under Free Pascal. Indy Original (now dormant) effort: Indy for Lazarus project 119 components Indy for FPC/Lazarus. Newer attempt Indy with Lazarus (Both Indy9 and Indy10) Castle Game Engine, a 3D game engine especially focused on VRML/X3D. Using ActiveXperts Serial Port Component with Delphi. ActiveXperts Serial Port Component is a software development kit (SDK) that enables the user to communicate to a device over a serial interface. Such a device can be: a weight indicator, a modem, a scanner, or any other device that is equiped with a serial port.
│English (en) │ español (es) │ français (fr) │
References: Tutorials/practical articles: Databases
|
- 4SQLDB tutorials and example code
- 4.3Connecting to MySQL from a Lazarus Application
- 7MySQL package: the low level units
Overview
You can use Free Pascal/Lazarus to access a MySQL database server. Also you can use MySQL Data access components (MyDAC) as a Lazarus component to connect Lazarus and MySQL. Lazarus components MyDAC are free to download.
Win64: please see warning here on not using certain FPC/Lazarus Win64 versions.
Advantages of MySQL:
- It is very widely used and available
- Though older versions had a deserved reputation of not being true RDBMSes, newer versions support ACID properties if properly set up (with the right storage backend)
Disadvantages of MySQL:
- The MySQL maintainers break binary compatibility between client library versions. This means that an FPC/Lazarus translation needs to be made for each new version, which slows things down.
- The license may be restrictive to some users (e.g. in commercial deployments). There are compatible, possibly less restrictive alternatives like MariaDB.
A lot of Lazarus/FPC users prefer Firebird or PostgreSQL databases for this reason.
MySQL licensing
Before a significant MySQL deployment, don't forget to read its license.
SQLDB
Lazarus 1.2 (with FPC 2.6.2), supports
- MySQL 4.0 client library
- MySQL 4.1 client library
- MySQL 5.0 client library
- MySQL 5.1 client library
- MySQL 5.5 client library (supported since Lazarus 1.0.8)
- MySQL 5.6 client library (supported since Lazarus <fill in>)
Newer versions of FPC/Lazarus may support newer MySQL client libraries.
Make sure you are using the correct connection component for your client library version. So if you have the client libraries installed for MySQL 4.1 then you have to use TMySQL41Connection component, even if the server is running version 4.0 or 5.0. The reason for this is that MySQL client libraries often break compatibility of their API so each version needs a different Pascal driver.
On *nix systems, the SQLDB code may look for the plain version of the library without version number suffixes. There are several ways you can deal with this:
- (on many Linuxes) installing the -dev version of the library
- symlinking your specific library name to the one FPC is looking for (rather hackish)
- use TSQLDBLibraryLoader to specify the library name before loading the connection
SQLDB tutorials and example code
BigChimp September 2012: note: a lot of this is duplicate code and could be consolidated. I propose to move as much as possible to the GUI-oriented SQLDB Tutorial1 and create a separate page FPC database tutorial to create a text mode sample
Get MySQL working in Linux or Windows
Follow the instructions in the MySQL User Manual. Make sure that the mysqld daemon runs reliably, and that all potential users (including root, mysql, yourself and anybody else that may need it) have as many privileges as they need, from as many hosts as may be needed (such as 'localhost', the local host's name, and other hosts on your network) as far as is consistent with security. It is preferable that all users including root have passwords. Test the action of the database system using the examples given in the manual, and check that all users really do have reliable access.
Get MySQL working for FPC in text mode
There is a directory with an example program in $(fpcsrcdir)/packages/base/mysql/. You can find the fpc source directory in Lazarus: Tools -> Options -> Files -> FPC source directory. Possible paths for the mysql directory are /usr/share/fpcsrc/packages/base/mysql/ (rpm install) or C:lazarusfpcsrcpackagesbasemysql (windows). This directory also contains the units mysql.pp, mysql_com.pp and mysql_version.pp. Before running the test script, you need to create a database called testdb: do this by logging into the mysql monitor (as root with full privileges) and issuing the following SQL statement
then make sure that all relevant users have appropriate access privileges to it
There is a script called mkdb which you should now try to run:
This will probably fail, as the system will not allow an anonymous user to access the database. So change the script using an editor so that the line invoking mysql reads:
and try running it again, entering your password when prompted. With luck you might have managed to create the test database: test it (while logged in to the mysql monitor) by issuing the mysql statement
You should see a table listing the ID, username and email address of some of the FPC developers.
Now try to run the test program testdb.pp (this may need to be compiled, and will almost certainly fail on the first attempt!!).
I found that the program could not connect to mysql for several reasons:
- My system (SuSE Linux v9.0) installs mysql v4.0.15, not the version3 for which the package was designed.
- The program needs to have user names and passwords to get access to the database.
- The compiler needs to know where to find the mysql libraries (IF YOU HAVEN'T INSTALLED THE MYSQL DEVELOPMENT LIBRARIES, DO SO NOW!)
I created a copy of testdb.pp called trydb.pp, rather than editing the original - this means that the original files still get fixed in subsequent CVS updates.I also copied the files found in the subdirectory mysql/ver40/ into the main mysql/ subdirectory, renaming them mysql_v4.pp, mysql_com_v4.pp and mysql_version_v4.pp, being sure to rename the units within each file correspondingly. I changed the uses statement in trydb.pp to
and the statement in mysql_v4.pp to
I added a line to /etc/fpc.cfg to point to my libraries:
The following step might not be necessary if the devel-libraries are installed as the links will be created for you, but it never hurts to check.I had to find the real name of the mysqlclint library in the /usr/lib directory and in my case I had to issue the shell command:
to make a symbolic link allowing FPC to find the library. For good measure I also created the link
and placed similar links in various other directories: not strictly necessary, but just in case ...!Some users might need to add the following link:
I modified trydb.pp to include user details, initially by adding host, user and password as constants:
Warning: This section looks extremely outdated. If you are still on MySQL 4 perhaps it is time to upgrade
I also found that I couldn't connect to mysql using the mysql_connect() call, but had to use mysql_real_connect() which has many more parameters. To complicate things further, the number of parameters seems to have changed between version3 (where there are seven) and version4 (where there are eight). Before using mysql_real_connect I had to use mysql_init() which is not found in the original mysql.pp but is found in mysql_v4.pp.
So the code for connection to the database is now:
Now - ready to start compiling trydb.pp?
success! Now run it:
whoopee! I got the listing of the FPC developers!
A few extra refinements: make the entry of user details and the mysql commands interactive, using variables rather than constants, and allow several SQL commands to be entered, until we issue the quit command: see the full program listing, where user details are entered from the console, and the program goes into a loop where SQL commands are entered from the console (without the terminal semicolon) and the responses are printed out, until 'quit' is entered from the keyboard.
See Sample Console Listing.
Connecting to MySQL from a Lazarus Application
This tutorial shows how to connect Lazarus to the MySQL database, and execute simple queries, using only the basic Lazarus components; it uses no Data Aware components, but illustrates the principles of interfacing with the database.
Create a new project in Lazarus:
A new automatically generated Form will appear.
Enlarge the form to fill about half of the screen, then re-name the form and its caption to 'TryMySQL'.
From the Standard Component tab place three Edit Boxes on the upper left side of the Form, and immediately above each box place a label. Change the names and captions to 'Host' (and HostLLabel,HostEdit), 'UserName' (and UserLabel, UserEdit) and 'Password' (with PasswdLabel and PasswdEdit). Alternatively you could use LabelledEdit components from the Additional tab.
Select the Passwd Edit box and find the PasswordChar property: change this to * or some other character, so that when you type in a password the characters do not appear on your screen but are echoed by a series of *s. Make sure that the Text property of each edit box is blank.
Now place another Edit box and label at the top of the right side of your form. Change the label to 'Enter SQL Command' and name it CommandEdit.
Place three Buttons on the form: two on the left under the Edit boxes, and one on the right under the command box.
Label the buttons on the left 'Connect to Database' (ConnectButton)and 'Exit' (ExitButton) and the one on the right 'Send Query' (QueryButton).
Place a large Memo Box labelled and named 'Results' (ResultMemo) on the lower right, to fill most of the available space. Find its ScrollBars property and select ssAutoBoth so that scroll bars appear automatically if text fills the space. Make the WordWrap property True.
Place a Status Bar (from the Common Controls tab) at the bottom of the Form, and make its SimpleText property 'TryMySQL'.
A screenshot of the Form can be seen here: Mysql Example Screenshot
Now we need to write some event handlers.
The three Edit boxes on the left are for entry of hostname, username and password. When these have been entered satisfactorily, the Connect Button is clicked. The OnCLick event handler for this button is based on part of the text-mode FPC program above.
The responses from the database should be converted into strings and displayed in the Memo box. Text mode Pascal write and writeln statements are capable of performing a lot of type conversion 'on the fly', but the use of a memo box for text output requires explicit conversion of data types to the correct string: so Pchar variables have to be converted to strings using StrPas, and integers have to be converted with IntToStr.
Strings are displayed in the Memo box using:
The ConnectButton event handler thus becomes:
The Text Box on the right allows entry of a SQL statement, without a terminal semicolon; when you are satisfied with its content or syntax, the SendQuery button is pressed, and the query is processed, with results being written in the ResultsMemo box.
The SendQuery event handler is again based on the FPC text-mode version, except that once again explicit type-conversion has to be done before strings are displayed in the box.
A difference from the text-mode FPC program is that if an error condition is detected, the program does not halt and MySQL is not closed; instead, control is returned to the main form and an opportunity is given to correct the entry before the command is re-submitted. The application finally exits (with closure of MySQL) when the Exit Button is clicked.
The code for SendQuery follows:
Save your Project, and press Run -> Run
Download example source code
Warning: Current versions of Lazarus/FPC require committing all MySQL transactions. This was not necessary in earlier versions. The code download likely will not work until it is updated.
A full listing of the program is available here Sample Source Code
Lazarus, MySQL and UTF-8
The following may be required for other codepages/character sets as well
Lazarus Examples
UTF-8 Unicode is a convenient multibyte character set encoding, that allows working with multilingual texts without requiring WideStrings. It is supported both by Lazarus SQLdb components and by MySQL since version 4.1 by choosing the appropriate character set.
However, simply setting this encoding as default for
- your tables and
- the MySQL connection component (e.g.
TMySQL51Connection.CharSet:='UTF8';
)
will result in incorrect storage and retrieval of UTF-8 strings: any accented/international character will show up as question mark (?). Apparently, the reason for this is that MySQL client library is compiled to expect Latin1 character set by default.
In order to enable proper communication between Lazarus, MySQL client library and MySQL server, additional two queries need to be executed each time a connection to the database is established:
and
Lazarus For Windows
The first query will ensure your application receives strings in correct encoding, and the second tells MySQL not to convert strings it receives from your application.
Simple MySQL Demo Using the TMySQL5xConnection Component
Here is code that functions as a quick demo to get up and running simply. As with all SQLDB components, make sure the database client library is in the correct place:
- on Windows: the DLL, e.g. libmysql.dll is put in the project output directory (where the executable is generated). Alternatively, you could also place it in your Windows/system32 directory
- on Linux/OSX: install the mysql client library in your path (e.g. using your distribution's package manager)
When distributing your application, make sure the proper MySQL client library is present on your user's computer. As this can be a problem, perhaps using a different database engine may make more sense.
Code-driven sample
The example below uses code to fill your controls with data. You can also use