2014-10-17 109 views
-4

我已經搜索了我的答案,只是發現某人的代碼中存在拼寫錯誤。爲什麼我沒有'ExecuteScalar'的定義?

我還未發現此代碼無定義爲ExecuteScalar()的原因。當我實際將行添加到SQL數據庫時,實際上我可能需要捕獲Customer_Id,因爲它是自動增量。

這裏是我的代碼有問題:

if (customer_IDTextBox == null) 
{ 
    sqlConnection.Open(); 
    string SQL = "SELECT MAX(Customer_ID) FROM Customer"; 
    int maxId = Convert.ToInt32(SQL.ExecuteScalar()); 
    sqlConnection.Close(); 
} 
+2

看到這是一個字符串擴展方法會很有趣。 – 2014-10-17 04:18:58

回答

2

您需要創建的SqlCommand一個實例,然後指定你的連接,並查詢到它。

請嘗試使用此代碼。 (有幾點建議,我已經將你的連接和命令包含在using語句中,所以不需要關閉任何東西......它們將被丟棄。並且,總是儘量創建連接和命令,儘可能靠近指向你需要它們的地方。)

int maxId = -1; 

if (customer_IDTextBox == null) 
{ 
    using (var sqlConnection = new SqlConnection(/* your connection string */)) 
    { 
     sqlConnection.Open(); 
     string query = "SELECT MAX(Customer_ID) FROM Customer"; 

     using (var sqlCommand = new SqlCommand(query, sqlConnection)) 
     { 
      maxId = Convert.ToInt32(sqlCommand.ExecuteScalar()); 
     } 
    } 
} 
相關問題