【问题标题】:vb.net SQL connection string, writing only last value in databasevb.net SQL连接字符串,只写数据库中的最后一个值
【发布时间】:2016-11-18 08:47:38
【问题描述】:

可能是一个非常简单的问题,但我遇到了一些问题。 目前我正在从 OLAP Sever 中提取数据并将其写入 SQL 数据库。我用下面的字符串创建了我的数据库。

   Dim strSQL As String =
            "CREATE TABLE Datab(" &
            "ID Int IDENTITY(1,1) PRIMARY KEY," &
            "No Int NOT NULL," &
            "Name NVarChar(40) NOT NULL," &
            "basicvalue NVarChar(40) NOT NULL," &
            "Datee Date NOT NULL," &
           ")"

我的连接如下:
将 dbConnection 调暗为新的 SqlConnection(connectionString)

        'A SqlCommand object is used to execute the SQL commands.
        Dim cmd As New SqlCommand(strSQL, dbConnection)
        Dim regDate As DateTime = DateTime.Now
        Dim strDate As String = regDate.ToString("yyyy-MM-dd")

        If IsError(mdsRet) = vbTrue Then
            MsgBox("Error Connecting: " & IsError(MdsGetLastError))
        Else
            '  MsgBox("Connected to Server: " + mdsRet)

            'Check the number of Cubes in OLAP
            If tables.TablesCount(srv) >= 0 Then

                dbConnection.Open()
                'Counter from 1 to nu. of Cubes
                cmd1.CommandType = System.Data.CommandType.Text
                For counter As Integer = 1 To tables.TablesCount(srv)
                    cmd1.CommandText = "INSERT INTO Datab(No, Name, basicvalue,datee) VALUES ('" & counter & "','" + tables.TablesName(srv, counter) + "','" & tables.TableGetInfo(srv, tables.TablesName(srv, counter), 56) & "','" & strDate & "')"


                    cmd1.Connection = dbConnection
                    cmd.ExecuteNonQuery()
                    cmd1.ExecuteNonQuery()
                    counter = counter + 1
                Next

            End If

        End If

        'close DB connection
        dbConnection.Close()

连接将行写入数据库,但不增加索引行,所以我得到数据库表中的最后一个值,即执行完成后.. 总共有大约 60 行要写入。

我尝试了不同的选项来增加计数器,但它不起作用。谁能帮忙解释一下。

谢谢

【问题讨论】:

  • 删除 counter = counter + 1,因为 For 循环将自动递增 counter。不确定tables.TablesName(srv, counter) 的结构,但是这些通常从0 开始。所以将For counter As Integer = 1 更改为For counter As Integer = 0,当您在此处插入('" & counter & "','" 时,只需将其更改为('" & (counter + 1) & "','"。您还需要查看 Parameters 而不是将字符串连接在一起。
  • 嗨@Jinx88909,我确实改变了它..如果我改变For counter As Integer = 0然后我得到一个从String到Double的SQL转换错误,当我插入('" & (counter + 1) & "','"然后它只是增加计数器,即当counter 它应该是 1 它写 2 ( 1+1)。
  • 是的,您需要从 0 开始才能使最后一位工作。我假设tables.TablesName 是从零开始的,这意味着第一条记录从 0 开始而不是 1?错误将是别的东西,它可能有助于通过使用参数来解决这个问题。所以cmd1.Parameters.Add()。从长远来看,开启 Option Strict 也有助于编码。

标签: sql-server vb.net


【解决方案1】:

我想通了,我真是个傻瓜.. 在每次执行时,它都在执行创建查询,这意味着它正在删除表并创建新表。

我从循环中删除了行cmd.ExecuteNonQuery(),并在循环执行之前添加了它。效果很好。

虽然感谢@Jinx88909

【讨论】:

  • 你知道吗,我错过了问题的顶部,并认为另一个 cmd 只是你在测试 :) 很高兴你已经对其进行了排序。
猜你喜欢
  • 2012-11-21
  • 2011-12-11
  • 2015-03-30
  • 2015-02-07
  • 2011-08-02
  • 2011-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多