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?

AccessのVBAでバインド変数を使ってINSERT、UPDATE、SELECT

Last updated at Posted at 2023-08-24

参照設定

Microsoft ActiveX Data Objects 2.8 Library
image.png

テーブル

この記事の例は下記ようなテーブルがある前提です。
image.png

INSERT

サンプル
'コマンド用意。
Dim com_ As New ADODB.Command
com_.ActiveConnection = CurrentProject.Connection

'SQLをセット。
com_.CommandText = "INSERT INTO t_1 (onamae, id) VALUES (@onamae, @id) "

'名前で指定できるバインド変数を使うよって設定。
com_.NamedParameters = True

'1レコード目。
com_.Parameters("@onamae") = "たきな'"
com_.Parameters("@id") = "1"
com_.Execute

'2レコード目。
com_.Parameters("@onamae") = "ち'さと"
com_.Parameters("@id") = "2"
com_.Execute

上記の結果は下記。
image.png

バインド変数名の先頭@について

この@は必須ではありません。
前述のサンプルは『カラム名』か『バインド変数』かが分かりやすいよう、 自分ルールで先頭に@をつけているだけ です。
なので下記コードでも動作に支障はありません。

'コマンド用意。
Dim com_ As New ADODB.Command
com_.ActiveConnection = CurrentProject.Connection

'SQLをセット。
com_.CommandText = "INSERT INTO t_1 (onamae, id) VALUES (onamae, id) "

'名前で指定できるバインド変数を使うよって設定。
com_.NamedParameters = True

'1レコード目。
com_.Parameters("onamae") = "たきな'"
com_.Parameters("id") = "1"
com_.Execute

'2レコード目。
com_.Parameters("onamae") = "ち'さと"
com_.Parameters("id") = "2"
com_.Execute

UPDATE

INSERTとほぼ同様。

サンプル
'コマンド用意。
Dim com_ As New ADODB.Command
com_.ActiveConnection = CurrentProject.Connection

'SQLをセット。
com_.CommandText = "UPDATE t_1 SET onamae = @onamae WHERE id = @id "

'名前で指定できるバインド変数を使うよって設定。
com_.NamedParameters = True

'1レコード目。
com_.Parameters("@onamae") = "たきなchang"
com_.Parameters("@id") = "1"
com_.Execute

'2レコード目。
com_.Parameters("@onamae") = "ちさとchang"
com_.Parameters("@id") = "2"
com_.Execute

SELECT

サンプル
'コマンド用意。
Dim com_ As New ADODB.Command
com_.ActiveConnection = CurrentProject.Connection

'SQLをセット。
com_.CommandText = "SELECT * FROM t_1 WHERE onamae = @onamae "

'名前で指定できるバインド変数を使うよって設定。
com_.NamedParameters = True

'バインド変数に値をセット。
com_.Parameters("@onamae") = "たき'なchang"

'SELECT結果をループ。
Dim rst_ As New ADODB.Recordset
rst_.Open _
    com_, _
    , _
    adOpenForwardOnly, _
    adLockReadOnly
Do Until rst_.EOF
    
    Debug.Print rst_.Fields("onamae").Value

rst_.MoveNext: Loop
rst_.Close

参考サイトさん

バージョン

Microsoft Windows [Version 10.0.19045.3393]
Microsoft Access for Microsoft 365 MSO (バージョン 2307 ビルド 16.0.16626.20170) 32 ビット

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?