今天在逛新闻组的时候无意中看到了SqlCommand.Prepare()方法。在IDbCommand接口上就定义了Prepare()方法,这个方法可以把CommandType为Text的SQL语句提前在数据库中编译为一个临时的StoredProcedure然后再执行,这样对于需要多次执行的DbCommand来说,可以提高一定的执行效率:)注意:请在指定了Command的Connection之后再调用Prepare()方法。
此方法在msdn上的介绍如下:
Creates a prepared (or compiled) version of the command on the data source.
public void OleDbCommandPrepareEx() {
int id = 20;
string desc = "myFirstRegion" ;
OleDbConnection rConn = new OleDbConnection("Provider=SQLOLEDB;Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;");
rConn.Open();
OleDbCommand command = new OleDbCommand(null, rConn);

// Create and prepare an SQL statement.
command.CommandText = "insert into Region (RegionID, RegionDescription) values (@id, @desc)" ;
command.Parameters.Add ( "@id", id) ;
command.Parameters.Add ( "@desc", desc) ;
command.Prepare() ; // Calling Prepare after having set the Commandtext and parameters.
command.ExecuteNonQuery();

// Change parameter values and call ExecuteNonQuery.
command.Parameters[0].Value = 21;
command.Parameters[1].Value = "mySecondRegion";
command.ExecuteNonQuery();
}
此方法在msdn上的介绍如下:
Creates a prepared (or compiled) version of the command on the data source.
Remarks
If the CommandType property is set to TableDirect, Prepare does nothing. If CommandType is set to StoredProcedure, the call to Prepare should succeed, although it may result in a no-op.
Example
The following example creates an instance of the derived class, OleDbCommand, and opens the connection. The example then prepares a stored procedure on the data source by passing a string that is a SQL Select statement and a string to use to connect to the data source.
[C#]




















分类:
Database
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架