QueryDef 引數化查詢方法

此方法將阻止使用者在其輸入中嵌入第二個 SQL 語句以供執行。

Dim strSQL As String
Dim db As DAO.Database
Dim qdf As DAO.QueryDef

strSQL = "PARAMETERS [FirstName] Text(255), [LastName] Text(255), [Phone] Text(255); " _
         & "INSERT INTO Employees (chrFirstName, chrLastName, chrPhone) " _
         & "VALUES ([FirstName], [LastName], [Phone]);"

Set db = CurrentDb

Set qdf = db.CreateQueryDef("", strSQL)
qdf.Parameters("FirstName") = Me!txtFirstName
qdf.Parameters("LastName") = Me!txtLastName
qdf.Parameters("Phone") = Me!txtPhone
qdf.Execute

Me!txtFirstName = vbNullString
Me!txtLastName = vbNullString
Me!txtPhone = vbNullString

qdf.Close
db.Close
Set qdf = Nothing
Set db = Nothing

有效引數型別:

  • DATETIME:用於日期(引數預計 VBA Date
  • SHORTLONG:對於整數(SHORT 期望 Integer,LONG 期望 Long)
  • SINGLEDOUBLE:浮點數(分別為 Single 和 Double)
  • VARCHARTEXT:用於琴絃
  • MEMOLONGTEXT:對於長度超過 255 個字元的字串