Why do I need OleDbCommand.Prepare()?

若如初见. 提交于 2019-12-11 06:38:14

问题


I'm working with a datagrid and adapter that correspond with an MSAccess table through a stored query (named "UpdatePaid", 3 paramaters as shown below) like so:

    OleDbCommand odc = new OleDbCommand("UpdatePaid", connection);

    OleDbParameter param;

    odc.CommandType = CommandType.StoredProcedure;

    param = odc.Parameters.Add("v_iid", OleDbType.Double);
    param.SourceColumn = "I";
    param.SourceVersion = DataRowVersion.Original;

    param = odc.Parameters.Add("v_pd", OleDbType.Boolean);
    param.SourceColumn = "Paid";
    param.SourceVersion = DataRowVersion.Current;

    param = odc.Parameters.Add("v_Projected", OleDbType.Currency);
    param.SourceColumn = "ProjectedCost";
    param.SourceVersion = DataRowVersion.Current;

    odc.Prepare();

    myAdapter.UpdateCommand = odc;

    ...

    myAdapter.Update();

It works fine...but the really weird thing is that it didn't until I put in the odc.Prepare() call.

My question is thus: Do I need to do that all the time when working with OleDb stored procs/queries? Why? I also have another project coming up where I'll have to do the same thing with a SqlDbCommand... do I have to do it with those, too?


回答1:


This is called, oddly enough, a prepared statement, and they're actually really nice. Basically what happens is you either create or get a sql statement (insert, delete, update) and instead of passing actual values, you pass "?" as a place holder. This is all well and good, except what we want is our values to get passed in instead of the "?".

So we prepare the statement so instead of "?", we pass in parameters as you have above that are going to be the values that go in in place of the place holders.

Preparing parses the string to find where parameters can replace the question marks so all you have to do is enter the parameter data and execute the command.

Within oleDB, stored queries are prepared statements, so a prepare is required. I've not used stored queries with SqlDB, so I'd have to defer to the 2 answers previous.




回答2:


I don't use it with SqlDbCommand. It seems as a bug to me that it's required. It should only be nice to have if you're going to call a procedure multiple times in a row. Maybe I'm wrong and there's a note in documentation about providers that love this call too much.




回答3:


Are you using the JET OLEDB Provider? or MSDASQL + JET ODBC?

You should not need to call Prepare(), but I believe that's driver/provider dependent.

You definitely don't need to use Prepare() for System.Data.SqlClient.



来源:https://stackoverflow.com/questions/155375/why-do-i-need-oledbcommand-prepare

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!