1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【C++Builder】FireDACでFDQueryを使用してSQL文を発行

Posted at

C++BuilderのFireDACを使ったデータベースアクセスの方法について調べても、Delphiのサンプルコードばっかりでパラメタ設定の方法に苦労したので書いておく。

使用しているのはC++Builder10.2
MySQL 5.7.29

C++BuilderからMySQLを使用する設定方法はこちら

事前準備

1.TFDConnectionとTFDQuery、TDataSource、TDBGridを画面に貼る
image.png

2.TFDConnectionの設定
TFDConnectionのアイコンをダブルクリックし、接続エディタでデータベースの情報を設定する
image.png

  1. TFDQueryのプロパティのConnectionに先ほど張り付けたFDConnectionが設定されていることを確認する。
    image.png

4.TDBGridのDataSourceに先ほど張り付けたDataSourceを設定する
image.png

5.DataSourceのDataSetに先ほど張り付けたFDQueryを設定する
image.png

SQL文のパラメタ指定方法

例えば、ボタンを押すとテキストエディタに入力した文字列をデータベースから取得したい場合は以下のようにする。

FDQuery1->SQL->Text = "select * from test where name = :name";
FDQuery1->ParamByName("name")->Value= Edit1->Text;
FDQuery1->Active=true;

数値を指定するときも同じ

FDQuery1->SQL->Text = "select * from test where id = :id";
FDQuery1->ParamByName("id")->Value= Edit1->Text.ToInt();

別の指定方法もある

FDQuery1->SQL->Text = "select * from test where id = :id";
FDQuery1->Params->ParamValues["id"]=Edit1->Text.ToInt();

パラメタが日付の場合はこんな感じ

TDateTime today=Now();
TDateTime befor1year=today-TDateTime(1,0,0);
FDQuery1->SQL->Text = "select * from test where registdate between :from and:to";
FDQuery1->Params->ParamValues["from"]=befor1year.FormatString("yyyy-mm-dd");
FDQuery1->Params->ParamValues["to"]=today.FormatString("yyyy-mm-dd");

以上

参考ページ
コマンドの実行FireDAC

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?