一个string()作为SQL表的列

时间:2013-05-14 05:56:49

标签: sql arrays vb.net string

我有一个我读入的csv文件,我将其创建为一个字符串(),现在我想将所有这些输入到SQL表中。 它应该变成这样: TIME字符串(0)字符串(1)字符串(2)...

我如何在vb.net中进行此操作,我通常只是使用一个小循环来做这样的事情,但我认为这不会起作用,因为它是一个SQL命令。

示例:

" dim sqlcreatetable As String = _

    "USE MainDB1" & vbCrLf & _

    "IF EXISTS (SELECT * FROM sysobjects WHERE Name = 'logging' AND TYPE = 'u')" & vbCrLf & _

    "BEGIN" & vbCrLf & _

    "DROP TABLE MainDB1.dbo.logging" & vbCrLf & _

    "END" & vbCrLf & _

    "Create Table logging (TIME NVarchar(20) NOT NULL,"
    For i As Integer = 1 To aantaltags
        If (i = aantaltags) Then
            sqlcreatetable += csvtagssplit(3 * i - 2) & ") nvarchar(20) NOT NULL)"
        Else
            sqlcreatetable += csvtagssplit(3 * i - 2) & ") NVarChar(20) NOT NULL,"
        End If
    Next
    Dim dbConnection As New SqlCommand(sqlcreatetable, connection)
    connection.Open()
    dbConnection.ExecuteNonQuery()
    connection.Close()</code>

数组的大小是可变的,所以我不能只使它成为一条超大的线。

1 个答案:

答案 0 :(得分:0)

创建表格字符串如下:

Dim objConn As New SqlConnection("Server=<servername>;uid=<userid>;pwd=<password>;database=<dbaname>")

Dim csvStr as String  //Suppose It has Whole CSV file as a string
Dim csvWithoutQuotes As String = csvStr.Replace("""",""); //I am assuming that csv's any string doesn't have comma
Dim csvStrArrayOfOneLine() As String = csvWithoutQuotes.split(vbCrLf);
Dim csvStrArray() As String = csvStrArrayOfOneLine(0).split(","); 
Dim csvStrLength as Integer = csvStrArray.Length

Dim cmdString as string = "Create Table logging (TIME NVarchar(20) NOT NULL,"

For i As Integer = 0 To csvStrLength 
If ( i = csvStrLength ) Then
    cmdString += "log(" & i.ToString & ") NVarChar(20) NOT NULL)"
Else 
    cmdString += "log(" & i.ToString & ") NVarChar(20) NOT NULL,"
End If
Next
objConn.Open()
Dim objCmd As New SqlCommand(cmdString, objConn)
objCmd.CommandType = CommandType.Text
objCmd.ExecuteNonQuery()

我不是vb.net程序员,但我尽力满足你的答案。如果有任何错误;请告诉我。