65.9K
CodeProject 正在变化。 阅读更多。
Home

复制 MySQL 表中的带自动增量键的记录

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0投票)

2012年7月27日

CPOL
viewsIcon

14196

如何在 MySQL 表中复制带自动增量键的记录。

引言

本技巧讨论如何在具有自动递增键的MYSql表中复制特定的记录。

背景

我已经使用MySql好几年了,并且遇到过需要在具有自动递增键的表中复制(或重复)记录的情况。

以下VB.NET函数是一个最近一直在帮助我的解决方案。

所以我决定与大家分享它!

Using the Code

这是一个公共共享的布尔函数,你可以从你的VB.NET代码中调用它:  

Public Shared Function copy_recod(ByVal tbl As String, _
		ByVal tbl_id_name As String, ByVal tbl_id_value As Long) As Boolean
        Dim dup_query As String = Nothing
        Dim tbl_dat As New DataTable
        Dim next_id As Long = 0
        Dim copy_query As String = Nothing
        Dim col_value As String = Nothing

        Dim did_it As Boolean = False

        dup_query = "select * from " & tbl & " _
        where " & tbl_id_name & "=" & tbl_id_value
        tbl_dat = retriveDataToDataGrid(dup_query)

        If Not tbl_dat Is Nothing Then
            ActionRecord("LOCK TABLES " & tbl & " WRITE")
            ActionRecord("insert into " & tbl & _
            "(" & tbl_id_name & ")values( NULL)")

            next_id = Val(get_single_field("select MAX_
            (" & tbl_id_name & ") from " & tbl, 0))

            ActionRecord("UNLOCK TABLES")

            copy_query = "update " & tbl & " set "
            For Each r As DataRow In tbl_dat.Rows
                For Each col As DataColumn In tbl_dat.Columns

                    If col.ColumnName <> tbl_id_name Then
                        col_value = r(col).ToString

                        If InStr(col.DataType.ToString, "String") > _
                        0 Or InStr(col.DataType.ToString, "Date") > 0 Then
                            copy_query = copy_query & col.ColumnName & _
                            "='" & col_value & "',"
                        Else

                            If IsDBNull(col_value) Or col_value.Length <= 0 Then col_value = 0


                            copy_query = copy_query & col.ColumnName & _
                            "=" & col_value & ","
                        End If

                    End If

                Next
            Next

            copy_query = copy_query.Remove(copy_query.LastIndexOf(","), 1)

            If Right(copy_query, 1) = "=" Then
                copy_query = copy_query & "'" & 0 & "'"
            End If

            copy_query = copy_query & " where " & _
            tbl_id_name & "=" & next_id
            If ActionRecord(copy_query) > 0 Then
                did_it = True
            End If
        End If

        Return did_it

关注点

为了让我创建一个适用于任何表的开放函数,无论字段数量如何,我必须使用足够的变量并设置检查点以确保代码干净且可用。

这段代码的重要部分是它识别字段类型并创建正确的复制SQL命令。

ActionRecord() 函数是我的运行查询的函数。因此,你可以将其更改为你的命令或启动 update 查询的函数。

历史

  • 2012年7月27日:初始版本
© . All rights reserved.