我正在尝试制作词汇表。我有一个带有列表框、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
我怎样才能使它正常工作?