2016-01-11 54 views
0

怎麼了夥計們,我有一些麻煩,此代碼我希望能跟大家能想出加入2代表具有相同主鍵SQL Server以C#

我有2個表(客戶&註冊)使用SQL Server

客戶

  1. 編號
  2. 名稱

註冊

  1. 編號
  2. 日期

我在我的C#程序的工作,我想向他們展示成listview,但我在這裏有錯誤是我的代碼:

public void listdata() 
    { 
     SqlDataReader reader = null; 

     listView1.Items.Clear(); 
     listView1.Columns.Clear(); 
     listView1.Columns.Add("ID", 55, HorizontalAlignment.Center); 
     listView1.Columns.Add("Tanggal Registrasi", 150, HorizontalAlignment.Center); 
     listView1.Columns.Add("Nama Pemohon", 150, HorizontalAlignment.Center); 

     System.Data.SqlClient.SqlConnection conn = konn.GetConn(); 
     try 
     { 
      conn.Open(); 
      string sql = "select*from Ms_Register a join Ms_Coba b on a.id = b.id where id='" + textBox1.Text + "'"; 
      SqlCommand command = new SqlCommand(sql, conn); 
      command.ExecuteNonQuery(); 
      conn.Close(); 

      //Check 
      reader = command.ExecuteReader(); 


      while (reader.Read()) 
      { 
       ListViewItem item1 = new  ListViewItem(reader["id"].ToString(), 0); 
       item1.SubItems.Add(reader["tanggal"].ToString()); 
       item1.SubItems.Add(reader["nama"].ToString()); 

       listView1.Items.Add(item1); 
      } 
     } 
     catch (Exception e) 
     { 
      MessageBox.Show(e.ToString()); 
     } 
     finally 
     { 
      conn.Close(); 
     } 

    } 

這兩個表都有相同的ID和錯誤說「不明確的列名」ID「」 任何人都有辦法解決這個問題?謝謝

+0

看起來像你的兩個表有'id'柱和讀者混淆約_which_'id'你想。你有沒有試過用完整的數據庫和列名得到它?順便說一句,'select *'通常不是個好主意。 –

+0

您正在通過客戶或註冊過濾?將其更改爲「where a.id ='」或「where b.id ='」。 – jpgrassi

回答

0

您所查詢的是錯的,如下更改:

string sql = "select * from Ms_Register a join Ms_Coba b on a.id = b.id where a.id='" + textBox1.Text + "'"; 

因爲這兩個表包含字段名相同,所以我們不得不提到其表的字段要在where子句

+0

我使用ur代碼,這就是答案:執行閱讀器需要一個開放和可用的連接。連接當前狀態是關閉的。怎麼了? –

+0

運行command.ExecuteNonQuery()後,您已關閉連接,因此讀者需要重新打開連接。在while循環完成執行後最好關閉連接。 – Bayeni

+0

現在可以工作,當我打開我的連接謝謝! –

2
select*from Ms_Register a join Ms_Coba b on a.id = b.id where id='" + textBox1.Text + "'" 
選擇

應該是WHERE a.idWHERE b.id,無所謂其在這種情況下,因爲它們是相同的

儘管這是非常糟糕的代碼,但您應該通過使用查詢參數來清理textBox1的值。您的代碼易受SQL注入攻擊。

https://en.wikipedia.org/wiki/SQL_injection

+0

你是否認爲不可能用相同的ID來獲取2表中的數據? –

+0

不,這是可能的,上面的答案是正確的。 – mikeb