为什么需要OleDbCommand.Prepare()? [英] Why do I need OleDbCommand.Prepare()?

查看:73
本文介绍了为什么需要OleDbCommand.Prepare()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用通过存储的查询(名为"UpdatePaid",如下所示的3个参数)与MSAccess表相对应的数据网格和适配器,如下所示:

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();

它工作正常...但是真正奇怪的是直到我放入 odc.Prepare()调用之前,它没有.

因此,我的问题是:使用OleDb存储的proc/查询时,我是否需要一直这样做?为什么?我还要提出另一个项目,在该项目中我必须使用SqlDbCommand做同样的事情...我也必须使用这些做吗?

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?

推荐答案

奇怪的是,这被称为准备好的语句,它们实际上非常好.基本上,您将创建或获取一个sql语句(插入,删除,更新),而不是传递实际值,而是传递?".作为占位符.这一切都很好,只是我们要传递的是我们的价值观而不是?".

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会分析字符串以查找参数可以替换问号的位置,因此您要做的就是输入参数数据并执行命令.

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.

在oleDB中,存储的查询是准备好的语句,因此需要准备.我没有在SqlDB中使用存储的查询,因此我不得不遵从前面的2个答案.

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.

这篇关于为什么需要OleDbCommand.Prepare()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆