OleDbCommand Parameters Collection

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
 
M

Mohammad

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top