添加到数据库的问题

时间:2015-05-16 14:42:45

标签: mysql database vb.net

我的程序有一种通过文本文件向数据库添加词典的方法。所述文本文件由一个单词,它的单词形式(即名词,动词等)和相关图像的文件名组成,所有这些都以下列形式格式化:

word#type#filename
word2#type#filename2

等等。为了避免重复单词条目,我将MySqlDataReader与查询结合使用以遍历所有行,然后添加尚未添加的任何行。代码如下所示:

Private Sub btnCreateBank_Click(sender As Object, e As EventArgs) Handles btnCreateBank.Click
    Dim newOpenDialog As New OpenFileDialog
    Dim newFileStream As FileStream = Nothing
    newOpenDialog.InitialDirectory = GetFolderPath(SpecialFolder.MyDocuments)
    newOpenDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
    newOpenDialog.FilterIndex = 1
    newOpenDialog.ShowDialog()
    Try
        newFileStream = newOpenDialog.OpenFile()
        If (newFileStream IsNot Nothing) Then
            Dim sr As New StreamReader(newFileStream)
            Dim fileContents As String = sr.ReadToEnd()
            Dim fileContentsArray() As String = Split(fileContents, vbNewLine)
            Dim fullSplitArray As New List(Of String)
            For i As Integer = 0 To fileContentsArray.Length - 1
                fullSplitArray.AddRange(Split(fileContentsArray(i).ToString, "#"))
            Next
            For j As Integer = 0 To fullSplitArray.Count - 1 Step 3
                Dim connString As String = "server=localhost;user=root;database=jakub_project;port=3306;password=password;"
                Try
                    Using conn As New MySqlConnection(connString)
                        conn.Open()
                        Dim command As New MySqlCommand("SELECT COUNT(word) FROM words WHERE word=@inputWord", conn)
                        command.Prepare()
                        command.Parameters.AddWithValue("@inputWord", fullSplitArray.Item(j))
                        Dim dataReader As MySqlDataReader = command.ExecuteReader()
                        While dataReader.Read()
                            If dataReader.Item(0) = 1 Then
                                MsgBox(fullSplitArray.Item(j) & " added to system.")
                            Else
                                Using conn2 As New MySqlConnection(connString)
                                    conn2.Open()
                                    Dim addCmd As New MySqlCommand("INSERT INTO words(word, wordType, wordFilename) VALUES(@inputWord, @inputType, @inputFilename);", conn2)
                                    addCmd.Prepare()
                                    addCmd.Parameters.AddWithValue("@inputWord", fullSplitArray.Item(j))
                                    addCmd.Parameters.AddWithValue("@inputType", fullSplitArray.Item(j + 1))
                                    addCmd.Parameters.AddWithValue("@inputFilename", fullSplitArray.Item(j + 2))
                                    addCmd.ExecuteNonQuery()
                                    MsgBox(fullSplitArray.Item(j) & " added to system.")
                                    conn2.Close()
                                End Using
                            End If
                        End While
                        dataReader.Close()
                        conn.Close()
                    End Using
                Catch ex As Exception
                    MsgBox("Error: " & ex.ToString())
                End Try
            Next
        End If
    Catch ex As Exception
        MsgBox("Error: " & ex.ToString())
    End Try
End Sub

我没有包含第二个连接的先前变体在第一次给了我正确的结果,添加了8行。然而,所有连续的尝试都发出了错误,这些错误源于所谓的缺乏第二个连接。但现在,所有使用此子例程的尝试都会输出一个这样的表。

+--------+----------------------+----------------------+--------------------------+
| wordID | word                 | wordType             | wordFilename             |
+--------+----------------------+----------------------+--------------------------+
|      1 | acorn                | noun                 | acorn.jpg                |
|      2 | beach                | noun                 | beach.jpg                |
|      3 | chicken              | noun                 | chicken.jpg              |
|      4 | dance                | verb                 | dance.jpg                |
|      5 | elbow                | noun                 | elbow.gif                |
|      6 | fight                | verb                 | fight.gif                |
|      7 | grow                 | verb                 | grow.jpg                 |
|      8 | hat                  | noun                 | hat.jpg                  |
|     11 | acorn noun acorn.jpg | beach noun beach.jpg | chicken noun chicken.jpg |
|     12 | dance verb dance.jpg | elbow noun elbow.jpg | fight verb fight.gif     |
+--------+----------------------+----------------------+--------------------------+

我想要的是在第一组行中看到的数据加载,而不是我现在在后两行中接收的数据。但我不确定问题的根源在哪里。

错误消息并非真正告诉我发生了什么。出现的第一条错误消息告诉我,数据对于它试图插入的列来说太长了。第二个错误告诉我,j循环中的整数For超出范围,现在正在发生,因为系统似乎读取整个字符串而不是三个子字符串。

1 个答案:

答案 0 :(得分:0)

如果我理解你, 对我来说,您的文本文件拆分序列可能存在缺陷。在您发布的代码中哪个不明显,因为您可能在找到错误后更正了错误?

至于错误...... 第一个错误告诉您相关字段的数据(您没有提到它是哪个字段)太大而无法进入已分配的空间。这也可以量化为由不正确的分裂引起的 在你的分裂序列中。

关于第二个错误,目前还不清楚,但我认为在纠正拆分问题后不会出现错误?

最后,建议您移动Command.Prepare,以便在添加完所有命令参数后进行。

结束您的额外信息后

在阅读下面的评论之后,我仍然认为问题的最初原因在于你的分裂程序。

在使用监视工具查看分割结果后,很明显发生了什么。您可以在下面看到观察窗口

Watch Window Data

更多的是,有两个单独的例程来检查单词是否存在,并且如果它不存在则添加一个新单词似乎更有意义。

通过将它们从主处理块中分离出来,可以更容易地看到正在发生的事情......

所以我已经做了并测试了它,似乎工作正常。 主要区别在于我跳过了您在数据文件中读取的步骤,并模拟了字符串中的内容....

Private Sub btnCreateBank_Click(sender As Object, e As EventArgs) Handles btnCreateBank.Click
'
Dim counta As Integer = 0
Dim fullSplitArray As New List(Of String)
Dim fileContents As String = ""
Dim fileContentsArray() As String
Dim tmpWord As String = Nothing
Dim tmpType As String = Nothing
Dim tmpFile As String = Nothing
Dim Test As Boolean = False
'
Try
  fileContents = "1#acorn#noun#acorn.jpg" & vbNewLine & "2#beach#noun#beach.jpg" & vbNewLine & "3#chicken#noun#chicken.jpg" & vbCrLf & "4#dance#verb#dance.jpg" & vbNewLine & "5#elbow#noun#elbow.gif" & vbNewLine & "6#fight#verb#fight.gif" & vbNewLine & "7#grow#verb#grow.jpg" & vbNewLine & "8#hat#noun#hat.jpg"
  fileContentsArray = Split(fileContents, vbNewLine)
  For i As Integer = 0 To fileContentsArray.Length - 1
    fullSplitArray.AddRange(Split(fileContentsArray(i).ToString, "#"))
  Next
  For j As Integer = 0 To fullSplitArray.Count - 1 Step 4
    Test = False
    Try
      Test = IsWordAlreadyListed(fullSplitArray(j + 1), tmpWord, tmpType, tmpFile)
      If Test Then
        MsgBox(fullSplitArray.Item(j + 1) & " already listed in system (" & Trim(tmpWord) & ", " & Trim(tmpType) & ", " & Trim(tmpFile) & ")")
      Else
        Test = AddNewRow(fullSplitArray(j + 1), fullSplitArray(j + 2), fullSplitArray(j + 3))
      End If
    Catch ex As Exception
      MsgBox("Error: " & ex.ToString())
    End Try
  Next
Catch ex As Exception
  MsgBox("Error: " & ex.ToString())
End Try
Test = Nothing
'
End Sub


Function IsWordAlreadyListed(ByVal ParamWord As String, ByRef pRtnWord As String, ByRef pRtnType As String, ByRef pRtnFile As String) As Boolean
'
'-> Locals
Dim iwalConn As Data.SqlClient.SqlConnection = Nothing
Dim iwalCmd As Data.SqlClient.SqlCommand = Nothing
Dim iwalAdapter As Data.SqlClient.SqlDataReader = Nothing
Dim iwalQuery As String = Nothing
'-> Init
IsWordAlreadyListed = False
iwalConn = New System.Data.SqlClient.SqlConnection()
iwalConn.ConnectionString = "YOUR-CONNECTION-STRING-HERE"
'-> Process Request
If Trim(paramword) <> "" Then
  iwalQuery = "SELECT * FROM words WHERE word='" & Trim(ParamWord) & "'"
  '-> Query Databanks
  iwalCmd = New Data.SqlClient.SqlCommand(iwalQuery, iwalConn)
  If iwalCmd.Connection.State = Data.ConnectionState.Closed Then iwalCmd.Connection.Open()
  iwalAdapter = iwalCmd.ExecuteReader(Data.CommandBehavior.CloseConnection)
  If iwalAdapter.HasRows Then
    iwalAdapter.Read()
    pRtnWord = iwalAdapter.GetValue(iwalAdapter.GetOrdinal("word"))
    pRtnType = iwalAdapter.GetValue(iwalAdapter.GetOrdinal("wordType"))
    pRtnFile = iwalAdapter.GetValue(iwalAdapter.GetOrdinal("wordFilename"))
    IsWordAlreadyListed = True
  End If
  If iwalCmd.Connection.State = Data.ConnectionState.Open Then iwalCmd.Connection.Close()
Else
  MsgBox("Error: Invalid or missing word parameter!")
End If
'-> tidy up
iwalCmd = Nothing
iwalAdapter = Nothing
iwalQuery = Nothing
iwalConn = Nothing
'
End Function

Function AddNewRow(ByVal ParamWord As String, ByVal ParamType As String, ParamFile As String) As Boolean
'
AddNewRow = False
Dim arnConn As System.Data.SqlClient.SqlConnection = Nothing
Dim arnConnString As String = "YOUR CONNECTION STRING HERE"
arnConn = New System.Data.SqlClient.SqlConnection(arnConnString)
arnConn.Open()
Try
  Using arnConn
    Dim addCmd As New System.Data.SqlClient.SqlCommand("INSERT INTO words(word, wordType, wordFilename) VALUES(@inputWord, @inputType, @inputFilename);", arnConn)
    addCmd.Parameters.AddWithValue("@inputWord", ParamWord)
    addCmd.Parameters.AddWithValue("@inputType", ParamType)
    addCmd.Parameters.AddWithValue("@inputFilename", ParamFile)
    'addCmd.Prepare()
    addCmd.ExecuteNonQuery()
    MsgBox(ParamWord & " added to system.")
    AddNewRow = True
  End Using
Catch ex As Exception
  MsgBox("Error: " & ex.ToString())
Finally
  arnConn.Close()
End Try

End Function