vb2008使用一个按钮插入和更新记录

时间:2013-02-12 15:27:42

标签: sql vb.net

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

列表框现在填充了数据库中的单词,当选择单词时,其定义将显示在textbox2中。

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

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

我已经有了更新部分,但我在插入新记录方面遇到了问题。我做不好。词汇表只有两个字段:单词,定义。这是我的代码:

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

帮助我正常工作。我明天要完​​成这个。任何想法将不胜感激。

2 个答案:

答案 0 :(得分: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 statement,无需使用全局变量来保持连接,因为您将每次重新打开连接你需要它的时间然后关闭。不要认为这不是高性能,因为ADO.NET实现了connection pooling(它是SqlServer的MSDN文章,但这个概念也适用于MySql)

答案 1 :(得分: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 - 非常感谢您的帮助先生,我会尝试使用您建议给我的东西..可能是我的下一个项目。上帝速度!! :)