我在C#
中編寫了一個Sql-Server-ce
應用程序。在'使用'語句中選擇@@ Identity
最近我一直在將我的代碼轉換爲使用using
語句,因爲它們更清晰。在我的代碼中,我有一個非常簡單的GetLastInsertedID
函數 - 它返回最後插入的ID。工作版本如下:
public static int GetLastInsertedID()
{
int key = 0;
try
{
SqlCeCommand cmd = new SqlCeCommand("SELECT CONVERT(int, @@IDENTITY)", DbConnection.ceConnection);
key = (int)cmd.ExecuteScalar();
}
catch (Exception ex)
{
MessageBox.Show("Could not get last inserted ID. " + ex.Message);
key = 0;
}
return key;
}
下面是不工作,一旦我把它包在using
語句代碼:
public static int GetLastInsertedID()
{
int key = 0;
try
{
using (SqlCeConnection conn = new SqlCeConnection(DbConnection.compact))
{
conn.Open();
using (SqlCeCommand cmd = new SqlCeCommand("SELECT CONVERT(int, @@IDENTITY)", conn))
key = (int)cmd.ExecuteScalar();
}
}
catch (Exception ex)
{
MessageBox.Show("Could not get last inserted ID. " + ex.Message);
key = 0;
}
return key;
}
是我得到的是specified cast is not valid
錯誤。雖然這個錯誤通常是不言自明的,但我不明白爲什麼我會在第二塊代碼中獲得它,但不是第一塊。該錯誤發生在行key = (int)cmd.ExecuteScalar();
上。
我在做什麼錯第二塊代碼?
「不行」你是什麼意思?它是否會拋出異常?如果我不得不猜測我會說一些東西被過早地處理掉了。 – Clint
對不起,noob錯誤沒有發佈錯誤。它被指定爲「無效」。我編輯了這個問題。 –
對不起,沒有看到您的評論!但無論如何都要在'key =(int)cmd.ExecuteScalar();'處放置一個斷點,將該命令放在監視窗口中,並檢查出現的類型。看起來,由於某種原因,儘管轉換,它不是一個整數。那麼你可能會更接近找出發生了什麼事情。 –