我堅持檢查數據庫中是否存在記錄。這很容易在PHP中,但我找不到一個很好的教程如何在vb.net中做到這一點。如果數據庫中不存在,我想從文本框中插入值。如果不使用vb.net插入,如何檢查記錄是否存在?
這裏是我的代碼:
Using SQLConnection As New MySqlConnection(connString)
Using sqlCommand As New MySqlCommand()
With sqlCommand
'check if record exist
'if not execute these
.CommandText = "INSERT INTO bookrecords (Title, Author, Edition, Publisher, ISBN) values (@title,@author,@edition,@publisher,@isbn)"
.Connection = SQLConnection
.CommandType = CommandType.Text
.Parameters.AddWithValue("@title", txtTitle.Text)
.Parameters.AddWithValue("@author", txtAuthor.Text)
.Parameters.AddWithValue("@edition", txtEdition.Text)
.Parameters.AddWithValue("@publisher", txtPublisher.Text)
.Parameters.AddWithValue("@isbn", txtISBN.Text)
End With
Try
SQLConnection.ConnectionString = "Server=localhost;Database=booksdb;Uid=root;Pwd=;"
SQLConnection.Open()
sqlCommand.ExecuteNonQuery()
iReturn = True
'MessageBox.Show("Connection Opened")
Catch ex As MySqlException
MessageBox.Show("Error: " & ex.ToString())
iReturn = False
Finally
SQLConnection.Close()
'MessageBox.Show("Connection Closed")
End Try
End Using
End Using
我只想@isbn是用於確定是否記錄已經存在的關鍵。
在'isbn'上添加'UNIQUE',使用'INSERT IGNORE'? – Wrikken 2013-03-10 09:07:58