2016-05-28 196 views
0

enter image description here我有兩個表,一個表的名稱是(memberform),它有列id,名稱,移動示例1,dimitris,69xxxxxxx和第二個表(組),列名稱,組名,memberid示例dimitris,dancegroup,1 (MEMBERID與ID相同) 我想提取到一個RichTextBox其中來自團體= combobox1組名,並在那裏從哪個組名存在排​​MEMBERID一樣的是memberform.id從多個表中選擇?

我試圖像這樣

東西
using (var command = new SqlCommand("select mobile from memberform where memberform.id=groups.memberid and groups.groupname='" + comboBox1.Text + "'", con)) // 
using (var reader = command.ExecuteReader()) 
+1

1.什麼是qour問題? 2給出完整的可驗證代碼 –

+0

我將如何編寫選擇代碼 – Dim

+0

@Dim你能檢查我的更新答案嗎? – Arulkumar

回答

1

原始SQL查詢是

SELECT M.mobile 
FROM memberform M 
JOIN groups G ON G.memberid = M.id 
WHERE G.groupname = 'dancegroup' 

同樣可以在你的SqlCommand寫成是

using (var command = new SqlCommand("SELECT M.mobile FROM memberform M JOIN groups G ON G.memberid = M.id WHERE G.groupname = '" + comboBox1.Text + "'", con)) 

UPDATE:

上述方法可以是可能的SQL注入攻擊,因此通過SqlParameter

明確地傳遞參數
using (var command = new SqlCommand("SELECT M.mobile FROM memberform M JOIN groups G ON G.memberid = M.id WHERE G.groupname = @GroupName", con)) 
{ 
    command.Parameters.Add(new SqlParameter("GroupName", comboBox1.Text); 
    using (var reader = command.ExecuteReader()) 
    .... 
+0

Downvoted因爲您不使用參數。 – Bauss

+0

@Bauss你的意思是'SqlParamter'還是簡單的'comboBox1.Text'? – Arulkumar

+0

sql參數,否則查詢打開到sql注入。 – Bauss

0

爲什麼不從第一個表中選擇,得到的數字,然後用它來從第二個表中選擇?

@Edit:

private void GetData() 
{ 
    // Get the ID using the name 
    string id, yourData; 
    SqlConnection con = new SqlConnection(connectionString); 
    SqlCommand cmd = new SqlCommand("SELECT * FROM Table1 WHERE [email protected]", con); 
    cmd.Parameters.Add("@name", "dimitris"); 
    con.Open(); 
    SqlDataReader reader = cmd.ExecuteReader(); 
    while (reader.Read()) 
     id = reader["Id"].ToString(); 
    con.Close(); 

    // Get whatever you want using that ID 
    cmd.CommandText = "SELECT * FROM Table2 WHERE [email protected]"; 
    cmd.Parameters.Add("@id", id); 
    con.Open(); 
    reader = cmd.ExecuteReader(); 
    while (reader.Read()) 
     yourData = reader["ColumnName"].ToString(); 
    con.Close(); 
}