【问题标题】:VB.NET Inserting data into database from data view gridVB.NET 从数据视图网格将数据插入数据库
【发布时间】:2017-09-08 05:47:58
【问题描述】:

我想问一下,在插入来自数据网格的所有数据时,我是否可以提高速度。

例如:

我目前有 10,000 条数据需要插入数据库 sql server。 现在,我想将所有数据插入数据库。 但是我觉得会很慢。 不使用for循环可以吗?

    Dim chk_cmd As SqlCommand
    Dim chk_con As SqlConnection
    Dim checker As SqlDataReader
    Dim chkint As Integer = 0
    Dim constring As String = "Data Source=exmag\sqlexpress;Initial Catalog=Stock;Integrated Security=true;"
    Try
        For Each row As DataGridViewRow In DataGridView1.Rows

            chk_con = New SqlConnection(constring)

            chk_con.Open()
            chk_cmd = New SqlCommand("SELECT stockId FROM stock WHERE stockId = '" & row.Cells("stockId").Value & "'", chk_con)
            checker = chk_cmd.ExecuteReader(CommandBehavior.CloseConnection)
            If checker.HasRows Then
                chkint += 1
            Else
                Using con_insert As New SqlConnection(constring), cmd_insert As New SqlCommand("INSERT INTO stock VALUES(@stockId,@id_android,@itemCode,@quantity)", con_insert)
                    cmd_insert.Parameters.AddWithValue("@stockId", row.Cells("stockId").Value)
                    cmd_insert.Parameters.AddWithValue("@id_android", row.Cells("id_android").Value)
                    cmd_insert.Parameters.AddWithValue("@itemCode", row.Cells("itemCode").Value)
                    cmd_insert.Parameters.AddWithValue("@quantity", row.Cells("quantity").Value)
                    con_insert.Open()
                    cmd_insert.ExecuteNonQuery()
                    con_insert.Close()
                End Using
            End If


        Next
    Catch ex As SqlException
        If ex.Number.Equals(2627) Then
            MsgBox("Primary Key DUPLICATED/Some Data are currently in the table.")
        End If
    End Try

    MsgBox(chkint & " Data has duplicated primary key!")

【问题讨论】:

  • 你当然不应该使用循环。您应该有一个包含数据的DataTabl;e,然后根据具体情况,使用SqlDataAdapter 或SqlBulkCopy 插入数据。后者速度更快,但有局限性。我的问题是,您最初是如何在 DataGridView 中获得 10,00 条记录的?肯定是用户没有手动输入它们,所以它们来自哪里?
  • 它们来自在线托管数据库。我把它放在表单加载中
  • 我一直在寻找一个可以将所有数据表的数据插入数据库的示例。但是还是找不到

标签: sql-server vb.net


【解决方案1】:

您可以使用DataTable 和DataAdapter 更新数据库

下面是一个简短的在线。

    // con = SqlConnection '
    // queryString = your SELECT query 
    Using da As New SqlDataAdapter()
        da.SelectCommand = New SqlCommand( _
        queryString, connection)
        Dim dt As New DataTable("TABLE_NAME")
        da.Fill(dt)
        // Loop through your collection 
        // Add new Row to datatable 
        // Populate new row 
        Dim drow As DataRow = dt.NewRow()
        drow("Example Field") = "Example String"
        // Update database 
        dt.Add(drow)
        da.update(dt)
    End Using

注意cmets 使用双斜杠而不是撇号,因为 SO 似乎用撇号错误地突出了语法。

【讨论】:

    【解决方案2】:

    这是执行此操作的一种方法;我用它来传输电子表格。 我同意 jmcilhinney 的观点,即在网格中获取 10000 条记录是没有意义的。

    // create a datatable
    Dim dt_eff As New DataTable
    dt_eff.Columns.Add("Element", GetType(String))
    dt_eff.Columns.Add("Eff", GetType(Decimal))
    dt_eff.PrimaryKey = New DataColumn() {dt_eff.Columns("Element")}
    
    // fill the datatable
    For row As Integer = 4 To 50
        newRow = dt_eff.NewRow
        newRow("Element") = wsComp.Cells(row, 1).Value.ToString
        newRow("Eff") = CDec(wsComp.Cells(row, 6).Value)
        dt_eff.Rows.Add(newRow)
    Next
    
    // send the datatable to a sp on SQL SERVER
    Dim param As SqlClient.SqlParameter
    Using selectcmd As New SqlClient.SqlCommand("[dbo].[LoadingTable_IntegrateIncoming]", trans.Connection, trans)
        selectcmd.CommandType = CommandType.StoredProcedure
        param = selectcmd.Parameters.AddWithValue("@Efficiencies", dt_eff)
        param.SqlDbType = SqlDbType.Structured 
        selectcmd.ExecuteNonQuery()
    End Using
    
    // on the server side: declare a table type
    CREATE TYPE [dbo].[TVP_Efficiencies] AS TABLE(
        [Element] [nvarchar](5) NOT NULL,
        [Eff] [decimal](18, 4) NOT NULL,
        PRIMARY KEY CLUSTERED 
    (
        [Element] ASC
    )WITH (IGNORE_DUP_KEY = OFF)
    )
    
    // and create a stored proc that consumes the datatable
    CREATE PROCEDURE [dbo].[LoadingTable_IntegrateIncoming] 
        @Efficiencies TVP_Efficiencies readonly
    AS
    BEGIN
        SET NOCOUNT ON;
        insert into efficiencies
        select * from @Efficiencies
    END
    

    【讨论】:

      猜你喜欢
      • 2020-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-21
      相关资源
      最近更新 更多