2012-01-11 63 views
3

我試圖在標籤中顯示SQL查詢結果,但沒有顯示。這是我的代碼:在asp.net中的標籤中顯示SQL查詢結果

 string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID = '" + ID.Text + "' "; 
    SqlCommand showresult = new SqlCommand(result, conn); 
    conn.Open(); 
    showresult.ExecuteNonQuery(); 
    string actresult = ((string)showresult.ExecuteScalar()); 
    ResultLabel.Text = actresult; 
    conn.Close(); 

需要幫助。謝謝!

+0

你試過調試嗎?你的查詢是否真的返回數據?如果是這樣,我不會建議使用(字符串)首先接收數據,因爲它來int,double等,然後當您將它分配給標籤做myVariable.ToString(); – 2012-01-11 01:46:25

+0

是的,查詢正在返回數據。我試圖使用int和字節,仍然無法正常工作。 – Eximus 2012-01-11 01:48:00

+0

Active列有哪些數據類型? – 2012-01-11 01:50:41

回答

1

那裏有錯字嗎?你有兩個調用數據庫:

showresult.ExecuteNonQuery(); 

這將不會返回值,我不知道爲什麼你會在那兒

string actresult = ((string)shresult.ExecuteScalar()); 

除非你有一個shresult變量,這個查詢應該錯誤。什麼是shresult變量?

8

試試這個。

string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID = '" + ID.Text + "' "; 
    SqlCommand showresult = new SqlCommand(result, conn); 
    conn.Open(); 
    ResultLabel.Text = showresult.ExecuteScalar().ToString(); 
    conn.Close(); 
+0

謝謝...它的工作原理... – Eximus 2012-01-11 02:16:45

+4

請不要連接你的查詢作爲字符串。使用'SqlCommand'參數可防止SQL注入。 – 2013-11-19 10:58:06

1

使用SqlParameter過濾結果和呼叫ExecuteScalar()ExecuteReader()方法。

string result = "SELECT ACTIVE FROM [dbo].[test] WHERE [email protected]"; 
SqlCommand showresult = new SqlCommand(result, conn); 
// If ID is int type 
showresult.Parameters.Add("@ID",SqlDbType.Int).Value=ID.Txt; 

// If ID is Varchar then 
//showresult.Parameters.Add("@ID",SqlDbType.VarChar,10).Value=ID.Txt; 

    conn.Open(); 
    string actresult = (string)showresult.ExecuteScalar(); 
    conn.Close(); 
    if(!string.IsNullOrEmpty(actresult)) 
     ResultLabel.Text = actresult; 
    else 
     ResultLabel.Text="Not found"; 
+1

這將導致一個例外... shresult未宣佈 – CCBlackburn 2012-01-11 02:17:19

+1

@CCBlackburn - 謝謝!我剛剛從OP複製了文本。 – adatapost 2012-01-11 02:19:00

1
using (SqlConnection conn = new SqlConnection(connectionString)) 
{ 
    string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID = @id"; 
    SqlCommand showresult = new SqlCommand(result, conn); 
    showresult.Parameters.AddWithValue("id", ID.Text); 

    conn.Open(); 
    ResultLabel.Text = showresult.ExecuteScalar().ToString(); 
    conn.Close(); 
} 

這將配置的連接,並在查詢中沒有字符串連接。

0
conn.Open(); 
string result = "SELECT ACTIVE FROM test WHERE ID = '" + ID.Text + "' "; 
SqlCommand showresult = new SqlCommand(result, conn); 

showresult.ExecuteNonQuery(); 
int actresult = ((int)showresult.ExecuteScalar()); 
ResultLabel.Text = actresult.Tostring(); 
conn.Close(); 
+0

請看OP的評論他已經嘗試過int,但它沒有解決它 – CarbineCoder 2013-11-21 07:40:07