Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hey guys,
I am building a query that will select data from the database based on the value 'RentDue'. I am trying to get the corresponding value 'id'. Given my code below, how will this be possible?

C#
string sql = "SELECT  (ID, RentDue) from Rooms " + "where RentDue = '" + 22 + "')";
                SqlCommand execsql = new SqlCommand(sql, cn);
                cn.Open();


Also, how can I handle multiple results? Once I have obtained the ID, I will appending it to a RichTextView, and I expect there will be more than one result every time the query runs.

Thank you!
Posted

1 solution

0) Don't use string concatenation to for an SQL statement; use a parameterized query.
1) If you are selecting a single value you can use ExecuteScalar
2) If you are selecting multiple values, then you will need something else -- perhaps ExecuteReader.

C#
string sql = "SELECT ID from Rooms where RentDue = @rentdue";
SqlCommand execsql = new SqlCommand(sql, cn);
execsql.Parameters.AddWithValue ( "@rentdue" , 22 ) ;
cn.Open();

... // What do you want to do with it?
 
Share this answer
 
Comments
Member 10490060 23-Nov-14 22:26pm    
Thank you very very much! Using ExecuteScalar I have managed to get the first value from the database. However, when there are two values returned by the query, it will only get one of them. This is what I am doing:

execsql.ExecuteNonQuery();

string result = "";
result = Convert.ToString(execsql.ExecuteScalar());

richTextBox1.AppendText(Environment.NewLine);
richTextBox1.AppendText(result);

How can I change this to get all the results, and display them in the richTextBox? Thank you!
PIEBALDconsult 23-Nov-14 22:30pm    
ExecuteScalar will get only one result, ExecuteNonQuery will return only a count of how many rows were affected. You may want ExecuteReader.

Don't use Convert.

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