OleDbCommand Parameters Collection

  • Thread starter Thread starter Adam
  • Start date Start date
A

Adam

Hey guys I’m pretty new to this parameterized commands thing and I don’t
know why this code isn’t working. I have a Connection object set up as
Conn, and a Rec object which is holding my values. This method is inside
a "Class Library" being called from a "Windows Form" if that means anything.

string strCmd = "INSERT INTO Table (Value,Value,Value,Value,Value)
VALUES ('?','?','?','?','?')";
OleDbCommand cmd = new OleDbCommand(strCmd,Conn);
cmd.Parameters.Add(Rec.Value1);
cmd.Parameters.Add(Rec.Value2);
cmd.Parameters.Add(Rec.Value3);
cmd.Parameters.Add(Rec..Value4);
cmd.Parameters.Add(Rec.Value5);

I keep getting this error:

“An unhandled exception of type 'System.InvalidCastException' occurred
in system.data.dll

Additional information: The OleDbParameterCollection only accepts
non-null OleDbParameter type objects, not Int32 objects.”

Any help or input would be appreciated

-Adam
 
Adam wrote:

Change this:
string strCmd = "INSERT INTO Table (Value,Value,Value,Value,Value)
VALUES ('?','?','?','?','?')";

To this:

string strCmd
= "INSERT INTO Table (Value1, Value2, Value3, Value4, Value5 )"
+ "VALUES ( ?, ?, ?, ?, ? ) //note no single quotes.
;

Then change this:
cmd.Parameters.Add(Rec.Value1);
cmd.Parameters.Add(Rec.Value2);
cmd.Parameters.Add(Rec.Value3);
cmd.Parameters.Add(Rec..Value4);
cmd.Parameters.Add(Rec.Value5);

To this:
cmd.Parameters.Add( "@Value1", OleDbType.VarChar, 10 ).Value =
Rec.Value1;
cmd.Parameters.Add( "@Value2", OleDbType.Integer ).Value = Rev.Value2;
..
..
And so on.

Note that you have to specify the data type of each parameter, I have
just used VarChar and Integer as examples.

Then it should work fine.
 
Back
Top