【问题标题】:Updating sQL Server from datagridview从 datagridview 更新 SQL Server
【发布时间】:2013-11-06 15:20:53
【问题描述】:

我已经搜索了这个解决方案并找到了非常接近的答案,但无法解决我需要的问题。我有一个使用 Access 表中的数据填充 datagridview 的表单。填充后,我需要将该信息附加到 sql server 中的表中。请问最好的方法是什么?感谢您的帮助

这是我的代码;

    'connect to access

    Dim myDBconn As New OleDbConnection("connection details here")

    ' SQL Statement  

    Dim sql As String

    sql = "SELECT * FROM tblCustomerUpdates"

    Dim adapter As New OleDbDataAdapter(sql, myDBconn)

    ' Gets the records from Access table and fills  adapter

    Dim dt1 As New DataTable("CustomerDetails")

    adapter.Fill(dt1)

    Dim sql1 As String

    sql1 = "SELECT * FROM tblCustomerDetails"

    Dim adapter1 As New OleDbDataAdapter(sql1, myDBconn)

    Dim cmd1 As New OleDbCommand(sql1, myDBconn)

    myDBconn.Open()

    Dim myreader As OleDbDataReader = cmd1.ExecuteReader

    myreader.Read()

    ' DataSource for the DataGridView  

    DataGridView2.DataSource = dt1

    'now need to grab data from the datagridview or adapter and append rows to a table in sql server?

【问题讨论】:

    标签: sql-server vb.net datagridview


    【解决方案1】:

    我的问题:adapter1.Fill(dt1) 之后的代码应该做什么?它再次执行相同的选择,并且只从选择中读取第一个结果 - 然后它什么都不做?

    除此之外:

    adapter.Fill(dt1) 之后你有一个数据表。你现在要做的是:

    1. 为您的 SQL 服务器创建一个 SqlConnection
    2. 使用正确的 INSERT 语句创建一个名为 sqlAdapterSqlDataAdapter
    3. 使用sqlAdapter.Update(dt1) 将表中的行插入到数据库中

    【讨论】:

      【解决方案2】:

      非常感谢您的回答。我想我正在用第二段代码寻找不同的选项。我发现它很复杂——在我看来有很多方法可以实现这一点。我已经设法让它按如下方式工作,但我必须使用 command.parameter 方法创建 24 个数据字段。如果有更简单的方法,请告诉我。谢谢

      Dim conn 作为新的 Data.SqlClient.SqlConnection 暗淡命令作为新的 Data.SqlClient.SqlCommand

          conn.ConnectionString = "conn string"
      
          command.CommandText = "insert into tblCustomerprocessing (custTitleID,custInits,custSurname,custAdd1) values (@title,@initials,@surname,@custadd1)"
      
          command.Parameters.Add("@title", SqlDbType.Int)
          command.Parameters.Add("@initials", SqlDbType.NVarChar)
          command.Parameters.Add("@surname", SqlDbType.NVarChar)
          command.Parameters.Add("@custadd1", SqlDbType.NVarChar)
      
          conn.Open()
      
          command.Connection = conn
      
          'load grid
      
          For i As Integer = 0 To DataGridView2.Rows.Count - 2
      
              command.Parameters(0).Value = Me.DataGridView2.Rows(i).Cells(1).Value
              command.Parameters(1).Value = Me.DataGridView2.Rows(i).Cells(2).Value
              command.Parameters(2).Value = Me.DataGridView2.Rows(i).Cells(3).Value
              command.Parameters(3).Value = Me.DataGridView2.Rows(i).Cells(4).Value
      
              command.ExecuteNonQuery()
      
          Next
      
          conn.Close()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-05-10
        • 1970-01-01
        • 1970-01-01
        • 2022-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多