快速为您服务。 我正在使用以下代码将记录插入我的mysql数据库中的两个表...
SQLConnection.ConnectionString = connectionstring
Try
If SQLConnection.State = ConnectionState.Closed Then
SQLConnection.Open()
Dim SQLStatement As String = "INSERT INTO hosts(name, description, host, type, port, hostname) VALUES('" & txtname.Text & "','" & txtdescription.Text & "','" & txthost.Text & "','" & cmbtype.Text & "','" & txtport.Text & "','" & Pinger.resolvedstatus.Text & "'); SELECT LAST_INSERT_ID()"
SaveData(SQLStatement)
SQLConnection.Open()
SQLStatement = "INSERT INTO credentials(hosts_linked_id, username, password, type) VALUES('" & hosts_linked_id & "','" & txtusername.Text & "','" & txtpwd.Text & "','" & cmbtype.Text & "')"
SaveData(SQLStatement)
Savedata()
位调用此函数...
Public Sub SaveData(ByRef SQLStatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
cmd.CommandText = SQLStatement
cmd.CommandType = CommandType.Text
cmd.Connection = SQLConnection
cmd.ExecuteNonQuery()
hosts_linked_id = CInt(cmd.ExecuteScalar())
SQLConnection.Close()
MsgBox("Host has been added - Host ID " & hosts_linked_id & "")
txtname.Text = ""
txtdescription.Text = ""
txthost.Text = ""
cmbtype.Text = ""
txtport.Text = ""
End Sub
代码正在工作,必要的记录被插入到'hosts'和'credentials'表中,但是在每个表中,记录被插入两次。
显然我不希望我的数据库中有重复记录,所以有人可以帮我阻止它执行两次插入吗?
提前致谢!!
答案 0 :(得分:1)
你叫它两次:
cmd.ExecuteNonQuery()
hosts_linked_id = CInt(cmd.ExecuteScalar())
一次为ExecuteNonQuery
,第二次为ExecuteScalar()
您需要删除其中一个。看一下代码,我想你可能需要在SaveData
方法中引入一个参数来说明要使用哪一个。
答案 1 :(得分:0)
cmd.ExecuteNonQuery()
hosts_linked_id = CInt(cmd.ExecuteScalar())
删除cmd.ExecuteNonQuery()
以避免插入两次