DELPHI 10.3使用FireDAC连接MSSQL数据库测试

IDE: DELPH10.3

DATABASE: MSSQLSERVER2022

新建一个简单的VCL工程,

所需组件:TButton;TFDManager;TFDConnection;TFDQuery;TDataSource; TDBGrid;

数据库连接配置文件:driver.ini,配置好,放置在可执行文件相同目录,所有控件不默认配置,TFDManager控件的ConnectionDefFileAutoLoad、DriverDefFileAutoLoad属性设置为False;

  driver.ini的内容大致如下:

[driver.ini]
Encoding=UTF8

[MSSQL_Demo]
DriverID=MSSQL
Server=127.0.0.1
Database=Northwind
User_Name=sa
Password=
MetaDefSchema=dbo
MetaDefCatalog=Northwind
ExtendedMetadata=True

主窗口pascal代码如下:

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
  FireDAC.Stan.Intf, FireDAC.Stan.Option,
  FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
  FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.MSSQL,
  FireDAC.Phys.MSSQLDef, FireDAC.VCLUI.Wait, Vcl.StdCtrls, Data.DB,
  FireDAC.Comp.Client, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf,
  FireDAC.DApt, FireDAC.Comp.DataSet, Vcl.Grids, Vcl.DBGrids;


const
  cNameConnDef = 'mylocalmssql1';
  cCDFName = 'driver.ini';

type
  TForm1 = class(TForm)
    Button1: TButton;
    FDManager1: TFDManager;
    FDConnection1: TFDConnection;
    FDQuery1: TFDQuery;
    DataSource1: TDataSource;
    DBGrid1: TDBGrid;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);

  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin

  FDQuery1.Connection := FDConnection1;
  FDQuery1.SQL.Add('select * from mycar.dbo.Products');
  FDQuery1.Prepare;
  FDQuery1.Active := True;
  DataSource1.DataSet :=   FDQuery1;
  FDQuery1.Close();
  FDQuery1.Open();
  DBGrid1.DataSource := DataSource1;

end;

procedure TForm1.FormCreate(Sender: TObject);

begin
   //动态加载数据库配置文件
  FDManager.ConnectionDefFileAutoLoad := False;
  FDManager1.ConnectionDefFileName := cCDFName;
  FDManager1.LoadConnectionDefFile;
  FDConnection1.ConnectionName :=  cNameConnDef;
  FDConnection1.Connected := True;
//  FDConnection1.Open();

end;


end.

经测试可以展现:

 

posted on 2023-06-07 17:40  jhoncooper  阅读(381)  评论(0编辑  收藏  举报