Reputation: 491
I'm using two times sqlreader cause i have to select from two different tables how can i do this with one code?Here is my code:
First Sqlreader:
SqlCommand sqlCmd = new SqlCommand("SELECT Name from Customers where name = '"+textview2.Text+"'", con);
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
textview1.Text = (sqlReader["Name"].ToString());
}
sqlReader.Close();
Second Read:
SqlCommand cmd = new SqlCommand("Select Mobile from Informations where Mobile = '"+textview3.Text+"'", con);
SqlDataReader sqlReader2 = cmd.ExecuteReader();
while (sqlReader2.Read())
{
textview4.Text = (sqlReader2["Mobile"].ToString());
}
sqlReader2.Close();
I want to create one code instead of two.
Upvotes: 0
Views: 44
Reputation: 216353
First of all you need to use parameterized queries. I invite you to search about why this is the mandatory way to build sql queries and drop as soon as possible the use of string concatenations. After that you can join the two commands together and use the NextResult method of the SqlDataReader to reach your second data
// Both commands text are passed to the same SqlCommand
string cmdText = @"SELECT Name from Customers where name = @name;
SELECT Mobile from Informations where Mobile = @mobile";
SqlCommand sqlCmd = new SqlCommand(cmdText, con);
// Set the parameters values....
sqlCmd.Parameters.Add("@name", SqlDbType.NVarChar).Value = textview2.Text
sqlCmd.Parameters.Add("@mobile", SqlDbType.NVarChar).Value = textview3.Text
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.HasRows)
{
// Should be only one record, but to be safe, we need to consume
// whatever there is in the first result
while(sqlReader.Read())
textview1.Text = (sqlReader["Name"].ToString());
// Move to the second result (if any)
if(sqlReader.NextResult())
{
// Again, we expect only one record with the mobile searched
// but we need to consume all the possible data
while(sqlReader.Read())
textview4.Text = (sqlReader["Mobile"].ToString());
}
}
sqlReader.Close();
By the way, you already know the name and the mobile, then why do you execute this code?
Upvotes: 2