2016-08-13 58 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

相關問題