回答
使用SqlCommand.ExecuteScalar()
和將其轉換爲int
:
cmd.CommandText = "SELECT COUNT(*) FROM table_name";
Int32 count = (Int32) cmd.ExecuteScalar();
是的,在那裏幾乎涵蓋這個爲好,只是改變了`INSERT INTO`的例子是你`SELECT`聲明.. – 2011-01-12 12:47:59
在這種情況下,總會有一個int類型的返回值。在更一般的情況下,你可能會得到一個DBNull的返回值,例如「從table1中選擇ssn,其中company_id ='112233'」。由於您無法將DBNull轉換爲您的返回數據類型,因此您可以在SQL中或在您的應用程序中進行測試並對其進行更改。 – SeaDrive 2011-01-17 21:50:54
你永遠不會擺脫伯爵()一個的DBNull http://msdn.microsoft.com/en-us/library/ms175997.aspx – 2011-01-17 22:01:42
SqlConnection conn = new SqlConnection("ConnectionString");
conn.Open();
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM table_name", conn);
Int32 count = (Int32) comm .ExecuteScalar();
你會得到錯誤轉化與
cmd.CommandText = "SELECT COUNT(*) FROM table_name";
Int32 count = (Int32) cmd.ExecuteScalar();
改用
string stm = "SELECT COUNT(*) FROM table_name WHERE id="+id+";" ;
MySqlCommand cmd = new MySqlCommand(stm, conn);
Int32 count = Convert.ToInt32(cmd.ExecuteScalar());
if(count > 0){
found = true ;
} else {
found = false ;
}
在C#中補充與SQL:
SqlConnection conn = new SqlConnection("ConnectionString");
conn.Open();
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM table_name", conn);
Int32 count = Convert.ToInt32(comm.ExecuteScalar());
if (count > 0)
{
lblCount.Text = Convert.ToString(count.ToString()); //For example a Label
}
else
{
lblCount.Text = "0";
}
conn.Close(); //Remember close the connection
- 1. MySQL從SQL查詢獲取數據(phpmyAdmin)
- 2. 獲取從SQL查詢計數的Moodle
- 3. SQL 2008年變更數據捕獲查詢性能問題(SP與直查詢)
- 4. 從參數化SQL查詢
- 5. 從SQL查詢
- 6. 從SQL查詢
- 7. 從SQL查詢
- 8. SQL查詢獲取
- 9. 如何從SQL查詢中獲取值?
- 10. SQL查詢來獲取從得分
- 11. SQL查詢來獲得不從表
- 12. SQL查詢從表中獲取記錄
- 13. 從Django查詢集獲取SQL
- 14. 獲得從子類SQL查詢項目
- 15. SQL查詢來獲取誰從位置
- 16. 獲取真/假從SQL查詢
- 17. 從SQL查詢中獲取產品
- 18. 從EF7查詢中獲取SQL代碼
- 19. 從SQL查詢獲取重複項?
- 20. 從SQL查詢獲取依賴關係
- 21. 從Oracle SQL查詢中獲取引起
- 22. SQL查詢從PHP VS直接SQL數據庫查詢
- 23. 參數查詢sql中的sql查詢
- 24. 使用SQL Server Profiler捕獲查詢結果
- 25. SQL服務器:在查詢錯誤捕獲
- 26. 如何捕獲在CakePHP頁面中運行的SQL查詢?
- 27. Jmeter監聽器用於捕獲SQL查詢
- 28. 從查詢中獲取單行值的SQL查詢
- 29. SQL獲得從一個查詢結果到另一個查詢
- 30. 如何從sql查詢獲取jpql查詢?
這個問題是吹起來! 38379意見! – Dinuka 2016-01-30 09:15:04