Оглавление Free Pascal: Доступ к базе данных: ODBC - MS Access, MySQL


В папке \examples есть файл testodbc.pp. Эта программа обеспечивает доступ к базам данных через ODBC.
Во-первых, создадим базу данных stud1.mdb при помощи MS Aceess. В этой БД одна таблица - Students1 с полями:

Заполним таблицу например, так:
1Ivanov105.12.1990
2Петров214.06.1985
Во-вторых, обеспечим доступ к созданной БД через ODBC:

В-третьих, данные этой конкретной базы данных вписываем в текст файла testodbc.pp

Текст программы с комментариями

Program TestODBC;

uses odbcsql;

var 
  DBDSn : Pchar;    // Это имя источника данных ODBC 
  Query : pchar;    // Это SQL-запрос к базе данных
  UserName, Password  : pchar;
  tt: text;
  
  db,qq,usn,pass: string;
  
Function ODBCSuccess (Res : Integer) : Boolean;

begin
  ODBCSuccess:= (res=SQL_SUCCESS) or (res=SQL_SUCCESS_WITH_INFO);
end;

Var
  EnvHandle  : SQLHandle;
  DBHandle   : SQLHandle;
  StmtHandle : SQLHSTMT;
  ResID      : Longint;
  ResName    : Array[0..255] of char; // Matches length of field+1
  ResEmail   : Array[0..255] of char;

Procedure FreeHandles;

begin
  If StmtHAndle<>0 then
    SQLFreeHandle(SQL_HANDLE_STMT,StmtHandle);
  If DBHandle<>0 then
    SQLFreeHandle(SQL_HANDLE_DBC,DBHandle);
  If EnvHandle<>0 then
    SQLFreeHandle(SQL_HANDLE_ENV,EnvHandle);
end;

Procedure DoError (Msg : String;ErrCode : Integer);

begin
  FreeHandles;
  Writeln(Msg,' Code : ',ErrCode);
  Halt(1);
end;

Procedure StartSession;

Var
  Res : Integer;

begin
  EnvHandle:=0;
  DBHandle:=0;
  StmtHandle:=0;
  Res:=SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, EnvHandle);
  if Res <> SQL_SUCCESS then
    DoError('Could allocate ODBC handle',Res);
  Res:=SQLSetEnvAttr(EnvHandle,SQL_ATTR_ODBC_VERSION, SQLPOINTER(SQL_OV_ODBC3), 0);
  If Not ODBCSuccess(res) then
    DoError('Could not set environment',Res);
  Res:=SQLAllocHandle(SQL_HANDLE_DBC, envHandle, DBHandle);
  If res<>SQL_SUCCESS then
    DoError('Could not create database handle',res);
  Res:=SQLConnect(DBHandle,PSQLCHAR(DBDSN),SQL_NTS,
                        PSQLChar(UserName),SQL_NTS,
                        PSQLCHAR(Password),SQL_NTS);
  If Not OdbcSuccess(res) then
    DoError('Could not connect to datasource.',Res);
end;

Procedure ExecuteStatement;

Var
  Res,ErrCode : LongInt;

begin
  Res:=SQLAllocHandle(SQL_HANDLE_STMT,DBHandle,stmtHandle);
  If not ODBCSuccess(res) then
    DoError('Could not allocate statement handle.',Res);
  { Bind result buffers.
    Note that for many queries, the result is not known on beforehand,
    And must be queried with SQLPrepare, SQLNumResulCols and SQLDescribeCol
    before the statement is executed.}
  SQLBindCol(stmtHandle,1,SQL_INTEGER,SQLPointer(@ResID),4,@ErrCode);
  SQLBindCol(stmtHandle,2,SQL_CHAR,SQLPointer(@ResName),256,@ErrCode);
  SQLBindCol(stmtHandle,3,SQL_CHAR,SQLPointer(@ResEmail),256,@ErrCode);
  // Now actually do it.
  Res:=SQLExecDirect(StmtHandle,Query,SQL_NTS);
  if not ODBCSuccess(res) then
    DoError('Execute of statement failed.',Res);
end;

Procedure ShowResult;

Var
  Count,Res : Longint;

begin
  Res:=SQLFetch(StmtHandle);
  Count:=0;
  While Res<>SQL_NO_DATA do
    begin
    Inc(Count);
    Writeln(tt,'Record: ',Count,' : ');
    Writeln(tt,ResId,' ',PChar(@ResName[0]),' ',Pchar(@ResEmail[0]));
    Res:=SQLFetch(StmtHandle);
    end;
end;

begin
  Assign(tt,'odbc1.txt'); 
  Rewrite(tt);
  write('Name of ODBC Source-> '); // Проблемы с русификацией
  readln(DB);
  DBDSn:= PChar(db);
  
  write('login (UserName) -> ');
  readln(usn);
  UserName:= PChar(usn);

  write('Password -> ');
  readln(pass);
  Password:= PChar(pass);  
  
  write('SQL  -> '); // select * from students1, 
  readln(qq);
  Query:= PChar(qq);
  StartSession;
  ExecuteStatement;
  ShowResult;
  FreeHandles;
  Close(tt);
end.

Работа с программой в сеансе DOS (БД MS Access):

E:\XRAN_RW_MyProg\FPC_FPC>testodbc3.exe
Name of ODBC Source-> students1
login (UserName) ->
Password ->
SQL  -> select * from students1

Результаты - в текстовом файле odbc1.txt

Работа с программой в сеансе DOS (БД MySQL):

E:\XRAN_RW_MyProg\FPC_FPC>testodbc3.exe
Name of ODBC Source-> unesco1
login (UserName) -> root
Password ->
SQL  -> select * from un_forum
File 'C:\mysql\\share\charsets\?.conf' not found (Errcode: 2)
Character set '#51' is not a compiled character set and is not specified in the
'C:\mysql\\share\charsets\Index' file

Результаты - в текстовом файле odbc1.txt

Примечания:
Описание источника данных ODBC MySQL
Rambler's Top100
Hosted by uCoz