2012-01-01 79 views
0

我正在開發一個Web應用程序,並且在代碼隱藏中,我需要從數據庫中的特定表中獲取ID列並將其轉換爲int。查詢是:如何將sql命令的結果轉換爲int變量?

string quizID = SELECT MIN(column_name) FROM table_name 

,我希望把它的價值在

int quizid 

這意味着我需要轉換,所以該怎麼做?

+1

爲什麼你得到它回爲一個字符串開始? (如果你要顯示真實的代碼而不是這個僞代碼,這會很有用。)ID列的類型是什麼? – 2012-01-01 11:58:48

回答

1

你會想要做這樣的事情:

using (SqlConnection conn=new SqlConnection(sql_string)) { 

    conn.Open(); 

    SqlCommand command=new SqlCommand(
     sql_query, 
     conn 
    ); 

    Int32 quizid=((Int32?)command.ExecuteScalar()) ?? 0; 

} 
2
int quizID = -1; 

    using (SqlConnection conn = new SqlConnection(connString)) 
      { 
       conn.Open(); 

       string cmdText = "SELECT MIN(column_name) FROM table_name"; 
       using (SqlCommand cmd = new SqlCommand(cmdText, conn)) 
       { 
        SqlDataReader reader = cmd.ExecuteReader(); 
        if (reader != null) 
        { 
         while (reader.Read()) 
         { 
          quizID = reader.GetInt32("columnname"); 
         } 
        } 
        reader.Close(); 
       }   
       conn.Close(); 
      } 
1
SqlCommand cmd = new SqlCommand("SELECT MIN(column_name) FROM table_name", conn); 

    try 
    { 
     conn.Open(); 
     int quizid = (Int32)cmd.ExecuteScalar(); 
    } 
    catch (Exception ex) 
    { 
     Console.WriteLine(ex.Message); 
    } 

conn是SqlConnection對象