Click here to Skip to main content
15,886,017 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a method which returns value from database to a string. Now i have a problem because there is more than one result of the SELECT and I need to change ExecuteScalar(); to something else. I want to have these SELECT results in one string.


What I have tried:

string GetModule (string aplS) 
            {
                SqlConnection maConn = new SqlConnection("Data Source=xxx;Initial 
                Catalog=xx;User ID=xx;Password=xxx");
                string query = "select distinct mod from MOD_slow where 
                 aplS='"+aplS+"'";
                System.Data.SqlClient.SqlCommand cmd = new 
                System.Data.SqlClient.SqlCommand(query, maConn);
                System.Data.DataTable dt = new System.Data.DataTable();
                macierzConn.Open();                
                var SavedString = (string)cmd.ExecuteScalar();
                SavedString= SavedString.TrimEnd();
                macierzConn.Close();
                return SavedString;                            

            }
Posted
Updated 26-May-20 5:44am
Comments
Maciej Los 26-May-20 8:45am    
Can you be more specific and provide more details?

Either use ExecuteReader:
C#
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand cmd = new SqlCommand("SELECT Age, Description FROM myTable WHERE ID = @ID", con))
        {
        cmd.Parameters.AddWithValue("@ID", myTextBox.Text);
        using (SqlDataReader reader = cmd.ExecuteReader())
            {
            while (reader.Read())
                {
                int age = (int) reader["Age"];
                string desc = (string) reader["Description"];
                Console.WriteLine($"{age}\n{desc}");
                }
            }
        }
    }

Or a SqlDataAdapter:
C#
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlDataAdapter da = new SqlDataAdapter("SELECT Age, Description FROM myTable WHERE ID = @ID", con))
        {
        da.SelectCommand.Parameters.AddWithValue("@ID", myTextBox.Text);
        DataTable dt = new DataTable();
        da.Fill(dt);
        myDataGridView.DataSource = dt;
        }
    }
 
Share this answer
 
Well, 1st up, look at that HORRIBLE, DANGEROUS SQL - please dont do this - please use paramterized SQL

SqlCommand cmd = new SqlCommand(
    "select field from table where value = @Value", conn);

    SqlParameter param  = new SqlParameter();
    param.ParameterName = "@Value";
    param.Value         = *********;  // your actual value here 

    cmd.Parameters.Add(param);
    reader = cmd.ExecuteReader();

    while(reader.Read())
    {
        // Do something with the query result here 
        string colValue = reader["Column/Field Name"].ToString();
    }


2nd, you should use a 'using block' where possible, and forget the manual
macierzConn.Close();

so :-
using SqlConnection maConn = new SqlConnection("Data Source=xxx;Initial Catalog=xx;User ID=xx;Password=xxx")
{
    using SqlCommand cmd = new SqlCommand(
        "select field from table where value = @Value", conn);
    {
        SqlParameter param  = new SqlParameter();
        param.ParameterName = "@Value";
        param.Value         = *********;  // your actual value here 

        cmd.Parameters.Add(param);
    
        using SqlDataReader reader = cmd.ExecuteReader() 
        {
            while(reader.Read())
            {
                // Do something with the query result here 
                string colValue = reader["Column/Field Name"].ToString();
            }
        } // Using SqlDataReader 
    } // Using SqlCommand 
} // SqlConnection 


That's pretty rough and needs tidying up, but its the 'more correct' way

You havnt actually said what you mean by
Quote:
results in one string.
maybe you use a StringBuilder and add to the string in the while(reader.Read() loop
 
Share this answer
 
Comments
aksimoN 26-May-20 12:08pm    
I tried this way but my main problem is WHILE because when I put it into a method and tried to return string colValue i get :"CS0103 The name 'colValue' does not exist in the current context"


string GetModule2(string aplSymbol) //szukanie modułu
            {
                using SqlConnection maConn = new SqlConnection("Data Source=xxx;Initial Catalog=xx;User ID=xx;Password=xxx");
                {
                using SqlCommand cmd = new SqlCommand("select field from table where value = @Value", maConn);
                {
                    SqlParameter param = new SqlParameter();
                    param.ParameterName = "@Value";
                    param.Value = aplSymbol;  // your actual value here 

                    cmd.Parameters.Add(param);

                        using SqlDataReader reader = cmd.ExecuteReader();
                    {
                        while (reader.Read())
                        {
                         string colValue = reader["Column/Field Name"].ToString();
                        }
                    } 
                } 
            } 
            return colValue;
        }
Garth J Lancaster 26-May-20 21:17pm    
I did say it was rough and needed a bit more work, we are not supposed to do all your work for you ... colValue is the bit that you need to fill in, since you didnt really explain 'results in one string' .. you could, for example
using SqlCommand cmd = new SqlCommand("select field from table where value = @Value", maConn);                {                    
  SqlParameter param = new SqlParameter();                    
  param.ParameterName = "@Value";                    
  param.Value = aplSymbol;  // your actual value here                     
  cmd.Parameters.Add(param);
                        
  using SqlDataReader reader = cmd.ExecuteReader();                    
  {                        
    StringBuilder colStr = new StringBuilder("");                        
    while (reader.Read())                        
    {                         
      string colValue = reader["Column/Field Name"].ToString();                         
      colStr.Append(colValue);                         
      colStr.Append(",");                        
    }                        
    return colStr.ToString();                    
  }                 
}

to get a comma separated list of values as a string, and then remove the last
return colValue;
shown in the major block of code.

It's up to you though, to adequately define the problem and what you need

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900