簡體   English   中英

如何檢索ADO.NET SqlCommand的結果?

[英]How do I retrieve the result of an ADO.NET SqlCommand?

好吧,我現在真的很累或很厚,但我似乎無法找到答案

我正在使用ASP.NET,我想在表中找到行數。

我知道這是SQL代碼: select count(*) from topics ,但是HECK如何將其顯示為數字?

我想要做的只是運行該代碼,如果它= 0顯示一件事,但如果它超過0顯示其他東西。 請幫助?

這就是我到目前為止所擁有的

string selectTopics = "select count(*) from topics";
// Define the ADO.NET Objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand topiccmd = new SqlCommand(selectTopics, con);
if (topiccmd == 0)
    {
        noTopics.Visible = true;
        topics.Visible = false;
    }

但我知道我錯過了一些嚴重的錯誤。 我一直在尋找年齡但找不到任何東西。

PHP非常簡單。 :)

請注意,必須先打開連接並執行命令,然后才能訪問SQL查詢的結果。 ExecuteScalar返回單個結果值(如果查詢將返回多列和/或多行,則必須使用不同的方法)。

注意使用using構造,它將安全地關閉並處理連接。

string selectTopics = "select count(*) from topics";
// Define the ADO.NET Objects
using (SqlConnection con = new SqlConnection(connectionString))
{
   SqlCommand topiccmd = new SqlCommand(selectTopics, con);
   con.Open();
   int numrows = (int)topiccmd.ExecuteScalar();
   if (numrows == 0)
    {
        noTopics.Visible = true;
        topics.Visible = false;
    }
}

ExecuteScalar是您正在尋找的。 (SqlCommand的方法)

順便說一句,堅持使用C#,PHP更容易實現。 它只是熟悉。

您需要打開連接這可能有效:

SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;

cmd.CommandText = "select count(*) from topics";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection;
sqlConnection1.Open();

reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.

sqlConnection1.Close();

類似的問題: C#'select count'sql命令錯誤地從sql server返回零行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM