【问题标题】:VB.net adding parent and child records to MySQL dbVB.net 将父子记录添加到 MySQL 数据库
【发布时间】:2011-12-17 10:03:36
【问题描述】:

我被要求创建一个程序,将记录插入到一​​个父表和多个子表中。我的问题是,我怎么知道父表的 PK 是什么,以便我可以将它作为 FK 添加到子表中?父级的 PK 是一个自动编号。正如我在标题中所说,我通过 ODBC 连接使用 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

我仍在编写代码,所以不确定它是否有效 杰森

【问题讨论】:

    标签: mysql vb.net odbc vb.net-2010


    【解决方案1】:

    看看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

    【讨论】:

    • 谢谢,我试试看!还有一个问题,如果子插入失败,我希望所有插入都失败。我可以在交易中这样做吗?
    • 是的,你可以。这就是交易的好处真正发挥作用的地方。只需知道您的批处理会变得更大更复杂,因为您还想在该语句中设置这些插入,但这是正确的方法。
    • 谢谢!你不会有任何使用 select last_insert_idI() 进行事务的示例代码吗?我以前没有在 vb.net 中处理过事务。谢谢
    • 如果有帮助,我也可以发布我拥有的交易 vb.net 代码
    • 不确定赞成票是什么意思,但我刚刚添加了正在处理的事务代码,如果有帮助的话
    【解决方案2】:

    你可以使用

    "; select last_insert_id()"
    

    在父表的插入末尾。然后使用

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

    获取结果键以在子插入中使用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-14
      相关资源
      最近更新 更多