SQLServerにInsert文発行@Excel マクロ・VBA

SQLServerに接続し、Insert文を発行します。

接続文字列を作成します。
ADODB.Connectionを生成し、接続を行います。

接続後は、Insert文を作成し、発行します。
(update,delete文も同じです。)



Sub test()

Dim con As ADODB.Connection

Dim connectionString As String
Dim server As String
Dim dbname As String
Dim timeout As String
Dim id As String
Dim password As String

'接続文字列
server = "localhost\SQLEXPRESS"
dbname = "dbname"
id = "sa"
password = "id"
connectionString = "Provider=Sqloledb;Data Source=" & server _
                & ";Initial Catalog=" & dbname _
                & ";Connect Timeout=15" _
                & ";user id=" & id _
                & ";password=" & password


On Error GoTo Err

'コネクション生成
Set con = New ADODB.Connection

'接続
con.Open (connectionString)

'SQL文
con.Execute ("insert into table(id,name) values(201,'名前')")

'クローズ
con.Close
Set con = Nothing

Exit Sub

'エラー
Err:
    Set con = Nothing
    MsgBox (Err.Description)

End Sub




Copyright (C) Excelマクロ・VBAのお勉強. All Rights Reserved.