Returning a single row

前端 未结 10 2341
野的像风
野的像风 2021-02-13 06:58

I\'m trying to return a single row from a database:

using (connection = new SqlConnection(ConfigurationManager.AppSettings[\"connection\"]))
{
    using (command         


        
10条回答
  •  忘了有多久
    2021-02-13 07:22

    To me it seems, you don't want a single row, only a single value:

    SqlConnection sqlConnection = new SqlConnection("Your Connection String");
    SqlCommand cmd = new SqlCommand();
    Object returnValue;
    
    cmd.CommandText = "SELECT TOP 1 col_name FROM Customers";
    cmd.CommandType = CommandType.Text;
    cmd.Connection = sqlConnection1;
    
    sqlConnection.Open();
    
    returnValue = cmd.ExecuteScalar();
    
    sqlConnection.Close();
    
    return returnValue.ToString(); //Note you have to cast it to your desired data type
    

提交回复
热议问题