Difference between revisions of "Lazarus Database Tutorial/pt"

From Lazarus wiki
Jump to navigationJump to search
Line 12: Line 12:
 
Siga as instruções no Manual do usuário MySQL. Certifique-se que o mysqld daemon está rodando satisfatoriamente, e que todos os potencias usuários(incluindo root, mysql,voce mesmo e qualquer outro quer possa necessita-lo) tenham os privilégios a eles necessários, para os possíveis hosts que possam necessita-lo(incluindo 'localhost', o hostname local, e outros hosts na sua rede) para manter consistencia e segurança. É preferivel que todos os usuários incluindo o root tenham passwords. Teste as ações do sistema de banco de dados usando os exemplos dados no manual do mysql, e certifique-se que todos os usuários sejam confiáveis no acesso.
 
Siga as instruções no Manual do usuário MySQL. Certifique-se que o mysqld daemon está rodando satisfatoriamente, e que todos os potencias usuários(incluindo root, mysql,voce mesmo e qualquer outro quer possa necessita-lo) tenham os privilégios a eles necessários, para os possíveis hosts que possam necessita-lo(incluindo 'localhost', o hostname local, e outros hosts na sua rede) para manter consistencia e segurança. É preferivel que todos os usuários incluindo o root tenham passwords. Teste as ações do sistema de banco de dados usando os exemplos dados no manual do mysql, e certifique-se que todos os usuários sejam confiáveis no acesso.
  
=== Get MySQL working for FPC in text mode ===
+
=== Comece a trabalhar com FPC no modo texto ===
There is a directory with an example program in $(fpc<b>src</b>dir)/packages/base/mysql/. You can find the fpc source directory in Lazarus: Environment menu -> Environment Options -> Paths tab -> FPC source directory. Possible paths for the mysql directory are /usr/share/fpcsrc/packages/base/mysql/ (rpm install) or C:\lazarus\fpcsrc\packages\base\mysql\ (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
+
Este é o diretório com programa de exemplo $(fpc<b>src</b>dir)/packages/base/mysql/. Voce pode encontrar código fonte do FPC (Free Pascal Compiler) no Lazarus: Menu Environment -> Environment Options -> Paths tab -> FPC source directory. Possivelmente o endereço para o mysql seja em /usr/share/fpcsrc/packages/base/mysql (RPM) ou c:\lazarus\fpcsrc\packages\base\mysql\ (no windows). Este diretório contém também as units mysql.pp, mysql_com.pp e mysql_version.pp. Antes de rodar o script de teste, voce necessita criar o banco de dados chamada testdb: faça isso logando-se no prompt do mysql (o root com todos os privilegios) e dando o seguinte comando:
CREATE DATABASE testdb;
+
CREATE DATABASE testdb;
then make sure that all relevant users have appropriate access privileges to it
+
Certifique-se que todos os usuário tenham privilegios de acesso apropriados:
 
  GRANT ALL ON testdb TO johnny-user IDENTIFIED BY 'johnnyspassword';  
 
  GRANT ALL ON testdb TO johnny-user IDENTIFIED BY 'johnnyspassword';  
 +
 
There is a script called mkdb which you should now try to run:
 
There is a script called mkdb which you should now try to run:
 
  sh ./mkdb
 
  sh ./mkdb

Revision as of 04:58, 6 March 2006

Deutsch (de) English (en) español (es) français (fr) Bahasa Indonesia (id) italiano (it) 日本語 (ja) Nederlands (nl) português (pt) русский (ru) 中文(中国大陆)‎ (zh_CN) 中文(台灣)‎ (zh_TW)

Introdução

Este tutorial mostra como usar o Lazarus com uma variedade de Bancos de dados.

O Lazarus suporta uma diversidade de banco de dados, entretanto os desenvolvedores instalam os pacotes mais adequados para cada um. Você pode acessar o banco de dados por código ou colocando componentes no formulário. Os componentes do tipo data-aware(que precisam de uma fonte de dados para funcionar) representam campos e são conectados ajustando a propriedade DataSource para apontar para o TDataSource. O Datasource representa a tabela e é conectado ao componente do banco de dados(exemplos: TPSQLDatabase, TSQLiteDataSet) ajustando a propriedade DataSet. Os componentes data-awaresão ficam localizados na aba "Data Controls". O Datasource e o Database são localizados na aba "Data Access".

Lazarus e MySQL

Comece a trabalhar com MySQL no Linux ou Windows

Siga as instruções no Manual do usuário MySQL. Certifique-se que o mysqld daemon está rodando satisfatoriamente, e que todos os potencias usuários(incluindo root, mysql,voce mesmo e qualquer outro quer possa necessita-lo) tenham os privilégios a eles necessários, para os possíveis hosts que possam necessita-lo(incluindo 'localhost', o hostname local, e outros hosts na sua rede) para manter consistencia e segurança. É preferivel que todos os usuários incluindo o root tenham passwords. Teste as ações do sistema de banco de dados usando os exemplos dados no manual do mysql, e certifique-se que todos os usuários sejam confiáveis no acesso.

Comece a trabalhar com FPC no modo texto

Este é o diretório com programa de exemplo $(fpcsrcdir)/packages/base/mysql/. Voce pode encontrar código fonte do FPC (Free Pascal Compiler) no Lazarus: Menu Environment -> Environment Options -> Paths tab -> FPC source directory. Possivelmente o endereço para o mysql seja em /usr/share/fpcsrc/packages/base/mysql (RPM) ou c:\lazarus\fpcsrc\packages\base\mysql\ (no windows). Este diretório contém também as units mysql.pp, mysql_com.pp e mysql_version.pp. Antes de rodar o script de teste, voce necessita criar o banco de dados chamada testdb: faça isso logando-se no prompt do mysql (o root com todos os privilegios) e dando o seguinte comando: CREATE DATABASE testdb; Certifique-se que todos os usuário tenham privilegios de acesso apropriados:

GRANT ALL ON testdb TO johnny-user IDENTIFIED BY 'johnnyspassword'; 

There is a script called mkdb which you should now try to run:

sh ./mkdb

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:

mysql -u root -p  ${1-testdb} << EOF >/dev/null

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

select * from FPdev;

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

uses mysql_v4

and the statement in mysql_v4.pp to

uses mysql_com_v4

I added a line to /etc/fpc.cfg to point to my libraries:

-Fl/lib;/usr/lib

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:

ln -s libmysqlclient.so.12.0.0 lmysqlclient

to make a symbolic link allowing FPC to find the library. For good measure I also created the link

ln -s libmysqlclient.so.12.0.0 mysqlclient

and placed similar links in various other directories: not strictly necessary, but just in case ...! Some users might need to add the following link:

ln -s libmysqlclient.so.12.0.0 libmysqlclient.so

I modified trydb.pp to include user details, initially by adding host, user and password as constants:

const
  host : Pchar= 'localhost';
  user : Pchar= 'myusername';
  passwd: Pchar = 'mypassword';

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:

{ a few extra variables}
var
  alloc : PMYSQL;
 
{main program fragment}
 
begin
 if paramcount=1 then
   begin
   Dummy:=Paramstr(1)+#0;
   DataBase:=@Dummy[1];
   end;
 
Writeln ('Allocating Space...');
 alloc := mysql_init(PMYSQL(@qmysql));
 Write ('Connecting to MySQL...');
 sock :=  mysql_real_connect(alloc, host, user, passwd, database, 0, nil, 0);
 if sock=Nil then
   begin
   Writeln (stderr,'Couldnt connect to MySQL.');
   Writeln (stderr, 'Error was: ', mysql_error(@qmysql));
   halt(1);
   end;
 Writeln ('Done.');
 Writeln ('Connection data:');
{$ifdef Unix}
 writeln ('Mysql_port      : ',mysql_port);
 writeln ('Mysql_unix_port : ',mysql_unix_port);
{$endif}
 writeln ('Host info       : ',mysql_get_host_info(sock));
 writeln ('Server info     : ',mysql_stat(sock));
 writeln ('Client info     : ',mysql_get_client_info);
 
 Writeln ('Selecting Database ',DataBase,'...');
 if mysql_select_db(sock,DataBase) < 0 then
   begin
   Writeln (stderr,'Couldnt select database ',Database);
   Writeln (stderr,mysql_error(sock));
   halt (1);
   end;
{... as original contents of testdb.pp}


Now - ready to start compiling trydb.pp?

 fpc trydb

success! Now run it:

 ./trydb

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.