UniDAC连接ORACLE数据库封装代码

本文介绍了一种封装的数据库连接与SQL执行方法,包括连接数据库、执行查询和更改操作的功能实现,以及异常处理机制。

MyMsgBox.pas是自定义的messagebox,所以才可使用MsgBox,自定义消息框下载地址

http://download.youkuaiyun.com/detail/wozengcong/6263775


unit UnitUniDAC;



interface


uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, MyMsgBox, cxGraphics, cxControls, Uni,
  UniProvider, OracleUniProvider;


var
  UniConnection: TUniConnection;


function SetUniConnection(sServer, sUserName, sPassWord: string): Boolean;
function GetUniConnection: TUniConnection;
function PrepareSql(UniQuery: TUniQuery; bQuery: Boolean; sMySql: string): Boolean;


implementation


{-------------------------------------------------------------------------------
  作者:      曾聪
  日期:      2013.09.20
  过程名:    SetUniConnection
  功能:      封装SQL连接数据库代码,主要含传入的连接数据库的参数
  参数:      sServer, sUserName, sPassWord: string
  返回值:    Boolean
  说明:      使用try......finally作为预留扩展内容
-------------------------------------------------------------------------------}


function SetUniConnection(sServer, sUserName, sPassWord: string): Boolean;
var


  bFlag: Boolean;
begin
  bFlag := True;
  try
    try
      if UniConnection <> nil then
        UniConnection.Free;
      UniConnection := TUniConnection.Create(nil);
      UniConnection.ConnectString := 'ProviderName=Oracle;Username=' + sUserName + ';Password=' + sPassWord + ';Server=' + sServer + ';LoginPrompt=False;';
      UniConnection.SpecificOptions.Values['Direct'] := 'True'; //设置TCP/TP协议(无客户端)连接模式为真
      UniConnection.Connected := True;
    except
      on E: Exception do
        begin
          bFlag := False; //可以把错误提示放在调用时判断,也可以在封装函数判断
          UniConnection.Connected := False;
          if Pos(UpperCase('ORA-01017'), UpperCase(e.Message)) <> 0 then
            MsgBox('对不起,您填入的服务器名称/用户名/密码错误,连接数据库失败!', '错误', MB_OK + MB_USERICON, 2, MB_ICONHAND)
          else if Pos(UpperCase('ORA-12154'), UpperCase(e.Message)) <> 0 then
            MsgBox('对不起,您填入的服务器名称错误,连接数据库失败!', '错误', MB_OK + MB_USERICON, 2, MB_ICONHAND)
          else if Pos(UpperCase('ORA-12541'), UpperCase(e.Message)) <> 0 then
            MsgBox('对不起,未检测到监听程序,请确认操作系统的〖服务组件〗中的监听服务已经启动,连接数据库失败!', '错误', MB_OK + MB_USERICON, 2, MB_ICONHAND)
          else if Pos(UpperCase('11001'), UpperCase(e.Message)) <> 0 then
            MsgBox('对不起,未检测到您填入的“服务器”,请确认服务器的IP地址或者计算机名称正确并且Ping命令测试连接正常,连接数据库失败!', '错误', MB_OK + MB_USERICON, 2, MB_ICONHAND)
          else
            MsgBox(PWideChar(WideString(e.Message)), '错误', MB_OK + MB_USERICON, 2, MB_ICONHAND); //显示详细错误信息
        end;
    end;
  finally
    Result := bFlag;
  end;
end;


{-------------------------------------------------------------------------------
  作者:      曾聪
  日期:      2013.09.20
  过程名:    GetUniConnection
  功能:      封装SQL连接ADO代码,判断是否已经连接,如果断开尝试连接
  参数:      无
  返回值:    TUniConnection
  说明:      主要在执行SQL前判断使用
-------------------------------------------------------------------------------}


function GetUniConnection: TUniConnection;
begin
  if UniConnection = nil then
    begin
      MsgBox('尚未创建数据库连接', '错误', MB_OK + MB_USERICON, 2, MB_ICONHAND);
      Result := nil;
      Exit;
    end;
  try
    if not UniConnection.Connected then
      UniConnection.Connected := True;
  except
    on E: Exception do
      MsgBox(PWideChar(WideString('调用GetADOConnection函数发生未知错误: ' + e.Message)), '错误', MB_OK + MB_USERICON, 2, MB_ICONHAND);
  end;
  Result := UniConnection;
end;


{-------------------------------------------------------------------------------
  作者:      曾聪
  日期:      2013.09.20
  过程名:    PrepareSql
  功能:      封装SQL语句执行函数
  参数:      adoQry: TUniQuery; bQuery: Boolean; sMySql: string
  返回值:    Boolean
  说明:      使用try......finally作为预留扩展内容
-------------------------------------------------------------------------------}


function PrepareSql(UniQuery: TUniQuery; bQuery: Boolean; sMySql: string): Boolean;
var
  bFlag: Boolean;
begin
  bFlag := True;
  with UniQuery do
    try
      try
        Connection := GetUniConnection;
        Close;
        SQL.Clear;
        SQL.Add(sMySql);
        if bQuery = True then
          try
            Open;
          except
            on E: Exception do
              begin
                bFlag := False;
                MsgBox(PWideChar(WideString('对数据库执行查询操作发生错误:' + e.Message + '请关闭工具后重试!')), '错误', MB_OK + MB_USERICON, 2, MB_ICONEXCLAMATION);
              end;
          end
        else
          try
            Connection.StartTransaction;
            ExecSQL;
            Connection.Commit;
          except on E: Exception do
              begin
                Connection.Rollback;
                bFlag := False;
                MsgBox(PWideChar(WideString('对数据库执行更改操作发生错误:' + e.Message + ', 为了数据安全,已经回滚到操作更改前状态,请关闭工具后重试!')), '错误', MB_OK + MB_USERICON, 2, MB_ICONEXCLAMATION);
              end;
          end;
      except
        on E: Exception do
          begin
            bFlag := False;
            ShowMessage(BoolToStr(bflag));
            MsgBox(PWideChar(WideString('执行SQL语句发生错误:' + e.Message + ',请关闭工具后重试!')), '错误', MB_OK + MB_USERICON, 2, MB_ICONEXCLAMATION);
          end;
      end;
    finally
      Result := bFlag;
    end;
end;


end.
Universal Data Access Components (UniDAC) is a powerful library of nonvisual cross-database data access components for Delphi, Delphi for .NET, C++Builder, and Free Pascal. The UniDAC library is designed to help programmers develop faster and cleaner cross-database applications. UniDAC is a complete replacement for standard database connectivity solutions and presents an efficient native alternative to the Borland Database Engine and dbExpress for access to Oracle, SQL Server, MySQL, InterBase, Firebird, SQLite, DB2, Microsoft Access, Advantage Database Server, Adaptive Server Enterprise, and other databases (using ODBC provider). UniDAC is based on the well-known Data Access Components from Devart such as ODAC, SDAC, MyDAC, IBDAC, and PgDAC. We have joined the experience of long-term successful development into one great product which provides unified access to popular databases such as Oracle, Microsoft SQL Server, MySQL, InterBase, Firebird, SQLite, DB2, Microsoft Access, Advantage Database Server, Adaptive Server Enterprise, and other databases (using ODBC provider). The UniDAC library is actively developed and supported by Devart Team. If you have questions about UniDAC, email the developers at unidac@devart.com or visit UniDAC online at http://www.devart.com/unidac/. Advantages of UniDAC Technology UniDAC is very convenient in setup and usage. It provides transparent server-independent interface for working with different databases. Selected database provider ensures the best way to perform operations on the server. Universal Data Access UniDAC provides transparent server-independent interfaces for working with different databases, and lets you change the client engine for specific server type just by changing single connection option. It means that you can easily switch between database servers in your cross-database UniDAC-based application. Server-Aware Providers UniDAC chooses the best way specific to the server to perform most operations. Every UniDAC data provider uses server-specific native connectivity. All operations with data are performed by providers automatically considering peculiarities of the selected database server. Optimized Code The goal of UniDAC is to enable developers to write efficient and flexible database applications. The UniDAC library is implemented using advanced data access algorithms and optimization techniques. Classes and components undergo comprehensive performance tests and are designed to help you write high-performance, lightweight data access layers. Compatibility with Other Connectivity Methods The UniDAC interface retains compatibility with standard VCL data access components like BDE. Existing BDE-based applications can be easily migrated to UniDAC and enhanced to take advantage of server-specific features. Development and Support UniDAC is a cross-database connectivity solution that has been actively developed and supported. UniDAC comes with full documentation, demo projects, and fast (usually within one business day) technical support by the UniDAC development team. Find out more about how to get help or submit feedback and suggestions to the UniDAC development team in the Getting Support topic. A description of the UniDAC components is provided in the Component List.
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值