2016-05-28 148 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(); 
}