“Must declare the variable @myvariable” error with ADO parameterized query

后端 未结 3 1578
春和景丽
春和景丽 2020-12-18 07:24

i am trying to use parameterized queries with ADO. Executing the Command object throws the error:

Must declare the variable \'@filename\'

相关标签:
3条回答
  • 2020-12-18 07:29

    try this

    uses ADODB, DB;
    ...
    ...
    ... and then in some event handler (e.g. button click),
    var 
      aCommand :TADOCommand;
    begin
      aCommand := TADOCommand.create(self);
      aCommand.ConnectionString := 'build the connection string or use TADOConnection and assign to Connection property instead of ConnectionString property';
      aCommand.commandText := 'INSERT INTO Sqm(Filename, data) VALUES(:filename, :data);';
      aCommand.parameters.paramByName('filename').value := 'test';
      aCommand.parameters.paramByName('data').value := 'some data';
      aCommand.execute;
      aCommand.free;
    end;
    

    I have been using parameter by names this way for TADOCommand and TADOQuery with no problem.

    0 讨论(0)
  • 2020-12-18 07:33

    As far i know ADO doesn't supports named parameters in SQL sentences (SELECT, INSERT, UPDATE), so you must use the ? char to indicate the parameter

    sql := 'INSERT INTO Sqm(Filename, data) VALUES(?, ?)';
    

    and then assign the parameters values in the same order as are used in the sql sentence.

    ADO 2.6 Introduces the NamedParameters property, but it seems which only works with stored procedures.

    0 讨论(0)
  • 2020-12-18 07:53

    Use Parameters.AddWithValue as shown below

      connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Jet OLEDB:Database Password=RainbowTrout;";
      InsertQry = "Insert into Sections(Name, PartNumber, VersionNumber, Channel, Address, Status, IPAddr) "
            + "values(@SectionName, @PartNumber, @VersionNumber, @Channel, @Address, @Status, @IPAddr)";
    
    
      NewCfgConnection.ConnectionString = string.Format(connectionString, ConfigFN);
      NewCfgCommand.Connection = NewCfgConnection;
      NewCfgCommand.CommandText = InsertQry;
      NewCfgConnection.Open();
    
      // Clear parameter values from last record
      NewCfgCommand.Parameters.Clear();
    
      // Insert record into sections table - set parameters
      NewCfgCommand.Parameters.AddWithValue("@SectionName", sSectionName);
      NewCfgCommand.Parameters.AddWithValue("@PartNumber", sPartNumber);
      NewCfgCommand.Parameters.AddWithValue("@VersionNumber", sVersionNumber);
      NewCfgCommand.Parameters.AddWithValue("@Channel", iChannel);
      NewCfgCommand.Parameters.AddWithValue("@Address", iAddress);
      NewCfgCommand.Parameters.AddWithValue("@Status", iStatus);
      NewCfgCommand.Parameters.AddWithValue("@IPAddr", iIP);
    
      NewCfgCommand.ExecuteNonQuery();
    
    0 讨论(0)
提交回复
热议问题