2011-10-28 134 views
2

我被要求創建一個記錄插入一個父表和多個子表的程序。我的問題是,我怎麼知道父表的PK是什麼,以便我可以將它添加爲孩子的FK?父母的PK是一個自動編號。正如我在我的標題中所述,我通過ODBC連接使用VB.net,mySQL。我必須通過代碼執行此操作,並且不能使用存儲過程。有什麼建議麼?VB.net增加家長和孩子記錄的MySQL數據庫

感謝

我的交易看起來是這樣的:

 Dim cmdText As String = "INSERT INTO candidate(first_name, last_name, phone1, phone2, email1, city, " _ 
        & " state, country, zip,primary_contact_id) VALUES (?,?, ?, ?,?,?, ?,?,?,?)" 

    If conn.State = ConnectionState.Closed Then 
     conn.Open() 
    End If 
    Dim SqlStatus As Integer 
    Dim trans As Odbc.OdbcTransaction = conn.BeginTransaction(IsolationLevel.ReadCommitted) 
    Dim cmd As OdbcCommand = New OdbcCommand(cmdText, conn, trans) 


    Try 
     cmd.Parameters.Clear() 
     cmd.CommandType = CommandType.Text 'The default is CommandType.Text 

     With cmd.Parameters 
      .Add("@first_name", OdbcType.VarChar).Value = fName 
      .Add("@last_name", OdbcType.VarChar).Value = lName 
      .Add("@phone1", OdbcType.VarChar).Value = phone 
      .Add("@phone2", OdbcType.VarChar).Value = mobilePhone 
      .Add("@email1", OdbcType.VarChar).Value = email 
      .Add("@city", OdbcType.VarChar).Value = city 
      .Add("@state", OdbcType.VarChar).Value = state 
      .Add("@country", OdbcType.VarChar).Value = country 
      .Add("@zip", OdbcType.VarChar).Value = zip 
      .Add("@primary_contact_id", OdbcType.Int).Value = getContactFK 
     End With 

     SqlStatus = cmd.ExecuteNonQuery 

     If Not SqlStatus = 0 Then 
      trans.Commit() 
      Me.Close() 
     Else 
      MsgBox("Not Updated") 
     End If 



    Catch ex As Exception 
     MsgBox(ex.Message) 
    Finally 
     cmd.Dispose() 
     trans.Dispose() 
    End Try 

我還在工作的代碼,所以不知道它的工作原理,只是還沒有 傑森

回答

3

看看How to Get the Unique ID for the Last Inserted Row

因爲你要通過ODBC,不能使用存儲過程,你將不得不執行兩個SQL語句一起( as a batch)。首先你的插入,然後SELECT LAST_INSERT_ID()

它應該是這個樣子:

INSERT INTO ... ; 
SELECT LAST_INSERT_ID(); 

既然你期望你需要從你的客戶端代碼執行的SELECT語句的結果。由於這是一個插入批處理操作,您還應該考慮using a transaction

+0

謝謝,我會試試看!還有一個問題,如果子插入失敗,我希望所有插入失敗。我可以在交易中做到這一點嗎? – jason

+0

是的,你可以。這就是交易的好處真正起作用的地方。只要知道你的批處理會變得更大和更復雜,因爲你也想在那個語句中設置這些插入,但這是正確的方法。 –

+0

謝謝!你不會有任何示例代碼與選擇last_insert_idI()做一個事務嗎?我以前沒有在vb.net中使用過事務。謝謝 – jason

3

您可以使用

"; select last_insert_id()" 

在你插入父表的末尾。然後用

Dim id as Integer = cint(command.ExecuteScalar()) 

要獲得所產生的關鍵在孩子使用插入

+0

謝謝,我也會試試這個! – jason

+0

+1簡明的VB代碼片段! –