【发布时间】: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