2016-08-13 53 views
0

我使用两次SQLReader的原因我不得不从两个不同的表我怎么能做到这一点有一个代码选择这里是我的代码:我怎样才能从一个代码中的两个不同的表中选择? ?

首先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(); 

二读:

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(); 

我想创建一个代码而不是两个。

+0

创建程序,你也可以结合结果 –

+0

这是我使用前例。如果我将使用union,我会得到以下错误:所有使用UNION,INTERSECT或EXCEPT运算符组合的查询在其目标列表中必须具有相同数量的表达式。 – DiH

+0

如果'Customers'和'Inf​​ormations'表之间存在关系,那么您可以使用sql join。 – ekad

回答

2

首先您需要使用参数化查询。我邀请您搜索为什么这是构建sql查询的强制方式,并尽快删除字符串连接的使用。之后,你可以加入两个命令一起使用SqlDataReader的数据NextResult方法来达到你的第二个数据

// 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(); 

顺便说一句,你已经知道了名字和手机,那你为什么执行该代码?

+0

我得到错误没有数据可用 – DiH

+0

不知道这是怎么发生的。在MSDN上查看此示例https://msdn.microsoft.com/en-us/library/haa3afyz(v=vs.110).aspx – Steve

+0

检查所做的更改是否解决了问题 – Steve

相关问题