0

I would like to use my sql query result in a variable at same time.How can i do?

var conn = new SqlConnection(@"Server=(localdb)\MSSQLLocalDB; AttachDbFileName=|DataDirectory|database.mdf;");
conn.Open();
var comm = new SqlCommand($"SELECT name FROM database WHERE age = 25", conn);
var reader = comm.ExecuteReader();
 while(reader.Read())
{
  string name =reader[0].ToString();

}
conn.Close();


if (name != textbox.Text)
{
 //do something
}
2
  • This will not be a single result. Unless something is really wierd, you should have more then one person of age 25 in your Database. Accordingly you need to map the query result to a array or list. If you really only expect a singel value (wich should only happen with Scalar Functions or you use something like a Primary key/Other unique), the ExecuteScalar is the way to go. Commented Apr 6, 2019 at 23:51
  • 3
    Just some general notes for later: 1. If you plan on allowing the user to select the values, you really want to use parametized queries. No point being the offscreen part in this Comic: xkcd.com/327 2.You want to close the connection way more reliable. a using block is the most reliable way. 3. You generally do not store "processed Data" in the Database. You store the birthday and calculate the age. Of course for practical reasons you might still cache the result somehow, as long as you are really certain you do not keep a old value. Commented Apr 6, 2019 at 23:56

2 Answers 2

1

Use a DataTable and you can easily access your rows data. Something like:

DataTable dt = new DataTable();
dt.Load(reader)

Then you can use the DataTable.Rows property.

DataRow row = dt.Rows[0];
string name = row["name"].ToString();
Sign up to request clarification or add additional context in comments.

Comments

0

you could use the DataAdapter instead :

var table = new DataTable(); 

using(SqlConnection con = new SqlConnection(@"Server=(localdb)\MSSQLLocalDB; AttachDbFileName=|DataDirectory|database.mdf;"))
using(SqlCommand command =  new SqlCommand($"SELECT name FROM database WHERE age = 25", con))
using(SqlDataAdapter adapter = new SqlDataAdapter(command))
{
    con.Open();
    adapter.Fill(table);
}


// if single row 
if (table.Rows[0].Field<string>("name") != textbox.Text)
{
 //do something
}

//if multiple rows 
for(int x = 0; x < table.Rows.Count; x++)
{
    if (table.Rows[x].Field<string>("name") !=  textbox.Text)
    {
     //do something
    }
}

1 Comment

It is not necessary to open the connection before DataAdapter.Fill(). The DataAdapter will open and close the connection for you; however if it finds it open it will leave it open. Not a problem here since you are using using blocks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.