2017-02-15 57 views
1

我要增量ID添加主鍵另一個表如何自動增量數據類型插入到另一個表C#

這裏是我的代碼

  int id = null; //this id is public 

      OleDbCommand command = new OleDbCommand("insert into Table1([ID], [Name] values (@ID, @Name)", connection); 
      command.Parameters.AddWithValue("@ID", id); 
      command.Parameters.AddWithValue("@ID", txtName.Text); 
      command.ExecuteNonQuery(); 
      command.Parameters.Clear(); 

添加到這個數據庫 add to this database

  OleDbCommand command2 = new OleDbCommand("insert into Table2([TableID], [OtherInfo], [OtherDocument] values (@TableID, @OtherInfo, @OtherDocument)", connection); 
      command2.Parameters.AddWithValue("@TableIDID", id); 
      command2.Parameters.AddWithValue("@OtherInfo", txtOtherInfo.Text); 
      command2.Parameters.AddWithValue("@OtherDocument", txtOtherDocument.Text); 
      command2.ExecuteNonQuery(); 
      command2.Parameters.Clear(); 

TAble2

i灣t每次我添加一個新的名稱ID字段也添加在其他表對不起我的英語感謝。

+1

我認爲你不需要添加任何值到該列數據類型本身說它的自動增量只是留下ID列 – Dandy

+0

但是。我如何將autoincrement數據類型添加到另一個表中? –

+0

你不需要在第二個表中增加。你可以做什麼是當你插入第一個表中的東西獲取最大(id)和插入到第二個表。 – Nitin

回答

2

因爲你的ID字段是自動編號,你不應該當您插入給它的值,你讓數據庫創建爲您

OleDbCommand command = new OleDbCommand("insert into Table1([Name] values (@Name)", connection); 

command.Parameters.AddWithValue("@Name", txtName.Text); 
command.ExecuteNonQuery(); 

現在的問題是如何將其恢復。這可以使用命令SELECT @@ IDENTITY

command.Parameters.Clear(); 
command.CommandText = "SELECT @@IDENTITY"; 
int id = Convert.ToInt32(command.ExecuteScalar()); 

最後,您可以使用檢索到的ID在你插入的其他表來完成,

這是不以MS-訪問所需的模式理解批處理命令。其他數據庫系統有一個更好的模式,只需一次訪問數據庫而不是兩次。 (當然,Access主要是一個桌面數據庫,這沒有太大區別)

+0

謝謝你回答我的問題,它有很多幫助。 :) –

相關問題