0

我正在尝试制作词汇表。我有一个带有列表框、2 个文本框和一个保存按钮的表单。

The listbox is now populated with words from the database, and when a word is selected, its definition will display in textbox2.

用户可以通过在 textbox1 中填写一个新词和在 textbox2 中填写其定义来添加一条记录,然后单击保存按钮。如果新单词已经存在,则不允许保存新记录,如果两个文本框之间存在空值也是如此。如果它不存在,它将被插入到表格中,并且新单词将被添加到列表框中。

用户还可以通过首先选择列表中的一个词然后编辑该词和/或定义并单击保存按钮来更新记录。

我已经让更新部分开始工作,但我在插入新记录时遇到了问题。我不能正确地做到这一点。词汇表只有 2 个字段:单词、定义。这是我的代码:

Dim myCmd As New MySqlCommand
Dim myReader As MySqlDataReader
Dim myAdptr As New MySqlDataAdapter
Dim myDataTable As New DataTable
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
    Call Connect()
    With Me
        If Blank() = False Then
            If Duplicate() = False Then
                STRSQL = "insert into glossary values (@word, @def)"
                myCmd.Connection = myConn
                myCmd.CommandText = STRSQL
                myCmd.Parameters.AddWithValue("word", txtNew.Text)
                myCmd.Parameters.AddWithValue("def", txtdefine.Text)
                myCmd.ExecuteNonQuery()
                myCmd.Dispose()
                MsgBox("Record Added")
                Dim word As String
                word = txtNew.Text
                lstword.Items.Add(word)
                'myConn.Close()
                'Me.FillListbox()
            Else
                myConn.Open()
                STRSQL = "Update glossary set word = @term, definition = @mean where word = @term"
                myCmd.Connection = myConn
                myCmd.CommandText = STRSQL
                myCmd.Parameters.AddWithValue("term", txtNew.Text)
                myCmd.Parameters.AddWithValue("mean", txtdefine.Text)
                myCmd.ExecuteNonQuery()
                myCmd.Dispose()
                MsgBox("Record Updated", MsgBoxStyle.Information, "New word added")
            End If
        End If
    End With


End Sub

Public Function Blank() As Boolean
    Call Connect()
    With Me
        If .txtNew.Text = "" Or .txtdefine.Text = "" Then
            Blank = True
            MsgBox("Cannot save! Term and definition should not contain null value", MsgBoxStyle.Critical, "Unable to save")
        Else
            Blank = False
        End If
    End With
End Function

Public Function Duplicate() As Boolean
    Call Connect()
    With Me
        STRSQL = "Select * from glossary where word = '" & txtNew.Text & "'"
        myCmd.Connection = myConn
        myCmd.CommandText = STRSQL
        If myDataTable.Rows.Count <> 0 Then
            Duplicate = True
            'MsgBox("Word already exist. Please check the word.", MsgBoxStyle.Critical, "Duplicate.")

        Else
            Duplicate = False
        End If
        myConn.Close()
    End With
End Function

这是我的连接模块:

Public myConnectionString As String
Public STRSQL As String
Public myConn As New MySqlConnection
Public Sub Connect()
    With myConn
        Try
            If .State = ConnectionState.Open Then
                .Close()
            End If
            myConnectionString = "Database=firstaidcqs;Server=localhost;Uid=root;Password="
            .ConnectionString = myConnectionString
            .Open()
            'MsgBox("Successful Connection")
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Connection Error")
            .Close()
        End Try
    End With
End Sub
Public Sub Disconnect()
    With myConn
        .Close()
        .Dispose()
    End With
End Sub

我怎样才能使它正常工作?

4

2 回答 2

0

您在上面的所有代码中都使用了全局变量。

myConn and myCmd 

特别是,您在 myCmd 上调用 Dispose,但我在任何地方都看不到使用 New 重新初始化对象。另外,暂时忘记 myCmd.Dispose 问题,您不会重置 myCmd 参数集合。这样,您最终会为执行的命令收集错误的参数,也不要忘记打开插入部分的连接。(并为两个部分关闭它)

您可以轻松避免使用不必要的全局变量

....
If Duplicate() = False Then
    STRSQL = "insert into glossary values (@word, @def)"
    Using myCmd = new MySqlCommand(STRSQL, myConn)
        myConn.Open()
        myCmd.Parameters.AddWithValue("word", txtNew.Text)
        myCmd.Parameters.AddWithValue("def", txtdefine.Text)
        myCmd.ExecuteNonQuery()
    End Using
    myConn.Close()
.....
Else
    STRSQL = "Update glossary set word = @term, definition = @mean where word = @term"
    Using myCmd = new MySqlCommand(STRSQL, myConn)
        myConn.Open()
        myCmd.Parameters.AddWithValue("term", txtNew.Text)
        myCmd.Parameters.AddWithValue("mean", txtdefine.Text)
        myCmd.ExecuteNonQuery()
    End Using
    myConn.Close()
.....

更好的解决方案是更改 Connect() 方法以返回初始化的连接,而不是使用全局变量。这样,您还可以在 Using 语句中包含连接的创建和销毁

 Using myConn as MySqlConnection = Connect()
 .......
 End Using

为此,您需要以这种方式更改 Connect 的代码

Public Function Connect() as MySqlConnection
    Dim myConn As MySqlConnection
    myConnectionString = "Database=firstaidcqs;Server=localhost;Uid=root;Password="
    myConn = New MySqlConnection(myConnectionString)
    myConn.Open()
    return myConn
End Sub

不需要Disconnect函数,因为您将始终使用将为您关闭连接的Using 语句,不需要有一个全局变量来保持连接,因为您将在每次需要时重新打开连接并在之后关闭。不要认为这不是高性能的,因为 ADO.NET 实现了连接池 (这是 SqlServer 的 MSDN 文章,但该概念也适用于 MySql)

于 2013-02-12T16:04:52.237 回答
0

耶!!我现在开始工作了:D(我的道歉,我花了很长时间才完成这个......我还在学习)。这是我的最终代码:

Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
    Call Connect()
    If Blank() = False Then
        If Duplicate() = False Then
            STRSQL = "insert into glossary values (@word, @def)"
            Using myCmd = New MySqlCommand(STRSQL, myConn)
                myConn.Open()
                myCmd.Parameters.AddWithValue("word", txtNew.Text)
                myCmd.Parameters.AddWithValue("def", txtdefine.Text)
                myCmd.ExecuteNonQuery()
            End Using
            myConn.Close()
            MsgBox("Record Added")
            Dim word As String
            word = txtNew.Text
            lstword.Items.Add(word)
            myConn.Close()
        Else
            STRSQL = "Update glossary set word = @term, definition = @mean where word = @term"
            Using myCmd = New MySqlCommand(STRSQL, myConn)
                myConn.Open()
                myCmd.Parameters.AddWithValue("term", txtNew.Text)
                myCmd.Parameters.AddWithValue("mean", txtdefine.Text)
                myCmd.ExecuteNonQuery()
            End Using
            myConn.Close()
            MsgBox("Record Updated", MsgBoxStyle.Information, "New word added")
            Dim str As String
            str = txtNew.Text
            myConn.Close()
        End If
    End If
End Sub

Public Function Blank() As Boolean
    Call Connect()
    With Me
        If .txtNew.Text = "" Or .txtdefine.Text = "" Then
            Blank = True
            MsgBox("Cannot save! Term and definition should not contain null value", MsgBoxStyle.Critical, "Unable to save")
        Else
            Blank = False
        End If
    End With
End Function

Public Function Duplicate() As Boolean
    Dim dset As New DataSet
    Call Connect()
    With Me
        STRSQL = "Select * from glossary where word = '" & txtNew.Text & "'"
        myCmd.Connection = myConn
        myCmd.CommandText = STRSQL
        myAdptr.SelectCommand = myCmd
        myAdptr.Fill(dset, "glossary")
        myDataTable = dset.Tables("glossary")
        If myDataTable.Rows.Count > 0 Then
            Duplicate = True
            'MsgBox("Word already exist. Please check the word.", MsgBoxStyle.Critical, "Duplicate.")

        Else
            Duplicate = False
        End If
        myConn.Close()
    End With
End Function

我仍然使用我的第一个模块,但我已经删除了 Disconnect() 函数。@Steve - 非常感谢您的帮助先生,我会尝试使用您对我的建议一段时间..也许在我的下一个程序中。神速!!:)

于 2013-02-13T05:41:28.517 回答