1
我經常使用下面的模式爲單線程應用程序創建SqlCommands。爲Webservice準備的SqlCommand
我現在正在創建一個web服務,我擔心這種模式不能同時處理來自多個客戶端的請求。
有沒有一種方法可以爲多個客戶端使用單個「準備好的」SqlCommand,而不是簡單地將函數鎖定爲只允許單個客戶端同時運行?
private static SqlCommand cmdInsertRecord;
public static void InsertRecord(String parameter1, String parameter2, SqlConnection connection, SqlTransaction transaction)
{
if (cmdInsertRecord == null)
{
//Create command
cmdInsertRecord = connection.CreateCommand();
cmdInsertRecord.CommandText = @"SQL QUERY";
//Add parameters to command
cmdInsertRecord.Parameters.Add("@Parameter1", SqlDbType.Int);
cmdInsertRecord.Parameters.Add("@Parameter2", SqlDbType.DateTime);
//Prepare the command for use
cmdInsertRecord.Prepare();
}
cmdInsertRecord.Transaction = transaction;
//Note SetParameter is an extension that handles null -> DBNull.
cmdInsertRecord.SetParameter("@Parameter1", parameter1);
cmdInsertRecord.SetParameter("@Parameter2", parameter2);
cmdInsertRecord.ExecuteNonQuery();
}
我想做這樣的事情,因爲這些命令被多次調用不同的值 - 這正是應該創建一個準備好的命令的情況。 – jzacharuk 2012-08-01 18:32:59
@jzacharuk - 我仍然沒有看到全局sqlcommand對象中的任何好處,爲什麼不能在需要時在本地聲明它並在完成使用時將其處置掉? – JonH 2012-08-01 18:36:47