【问题标题】:ACCESS/SQL - Too Few ParametersACCESS/SQL - 参数太少
【发布时间】:2013-11-13 17:46:45
【问题描述】:

我正在使用下面的代码在“事务表”中创建新记录,插入语句的第二行抛出错误:参数太少。我已经仔细检查了所有字段名称都是正确的。还有什么可能导致此类错误?

' Modify this line to include the path to Northwind
' on your computer.
Set dbs = CurrentDb

Dim vblCustomerID As String
Dim vblMealType As String
Dim Charge As Currency
Dim vblDate As String
vblDate = Format(Date, "yyyy-mm-dd")
txtCustomerID.SetFocus
vblCustomerID = txtCustomerID.Text

txtMealType.SetFocus
vblMealType = txtMealType.Text

txtCharge.SetFocus
vblCharge = txtCharge.Text

dbs.Execute "INSERT INTO dbo_Transactions" _
    & "(CustomerID, MealID, TransactionAmount, TransactionDate) VALUES " _
    & "(" & vblCustomerID & ", " & vblMealType & ", " & vblCharge & ", " & vblDate & ");"
dbs.Close

【问题讨论】:

  • 执行SQL时请使用parameterized queries;否则,您将极易受到 SQL 注入攻击。这也应该可以解决您的问题。
  • 我强烈建议您更改您的代码,以便您首先创建 SQL 字符串并将其分配给一个变量,然后 dbs.Execute 该变量。这样,您可以在变量处设置断点并查看 Access 认为 SQL 字符串是什么。大多数情况下,Access 认为的和您认为的完全不同。
  • 你确定你的所有变量都有值吗?

标签: sql database ms-access


【解决方案1】:

正如其他人所建议的那样,使用参数化查询是一种非常更好的方式来做你想做的事情。试试这样的:

Dim qdf As DAO.QueryDef
Set qdf = dbs.CreateQueryDef("", _
        "PARAMETERS prmCustomerID Long, prmMealID Long, prmTransactionAmount Currency, prmTransactionDate DateTime;" & _
        "INSERT INTO dbo_Transactions (CustomerID, MealID, TransactionAmount, TransactionDate) " & _
        "VALUES ([prmCustomerID], [prmMealID], [prmTransactionAmount], [prmTransactionDate]) ")
qdf!prmCustomerID = txtCustomerID.Value
qdf!prmMealID = txtMealType.Value
qdf!prmTransactionAmount = txtCharge.Value
qdf!prmTransactionDate = Date()
qdf.Execute dbFailOnError
Set qdf = nothing

【讨论】:

    【解决方案2】:

    您加载到 vbl 字段中的任何文本字段是否包含此类特殊字符?

    , ' " 
    

    一个完美的 SQL 插入命令的文本字段中的所有内容都可能搞砸,我敢打赌这就是这里发生的事情。

    如果您在此处实际使用参数会更好,而不是将文本框中的文本直接加载到您的 SQL 查询中,因为您正在接受 SQL 注入。如果有人输入怎么办

    "; Drop Table dbo_Transactions;
    

    在您的一个文本框中运行此查询?然后你的数据库就完全搞砸了,因为有人刚刚删除了你的一张表。

    一些关于使用参数来防止此问题的信息的链接,我敢打赌这也将解决您遇到的参数太少的问题。

    http://forums.asp.net/t/886691.aspx

    http://sqlmag.com/blog/t-sql-parameters-and-variables-basics-and-best-practices

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-11
      相关资源
      最近更新 更多