Returning a single row

前端 未结 10 1438
轻奢々
轻奢々 2021-02-13 06:55

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:35

    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
    

提交回复
热议问题