我在使用VB.net应用程序将值插入MySQL
时遇到问题。我可以连接到db,但不能插入值。我已经下载了DLL并将其作为参考附加。我也已经编写了查询并将其直接插入数据库并且它可以工作。我已经尝试了多种方法来编写我在本网站上找到的示例,但我仍然无法让它工作。这是我试图开始工作的代码:
Try
MysqlConn = New MySqlConnection("server=localhost;userid=User;password=******;database=Targets")
MysqlConn.Open()
Dim sqlCommand As New MySqlCommand
sqlCommand.CommandType = CommandType.Text
sqlCommand.CommandText = "insert into Victims(UserName, Machine, IP) values('" + strUser + "','" + strMachine + "','" + strIPAddress + "')"
Dim strRD As MySqlDataReader
strRD = sqlCommand.ExecuteReader()
MysqlConn.Close()
MessageBox.Show("connected")
Catch ex As MySqlException
MessageBox.Show("error")
我已经在代码的前面声明了查询语句中使用的变量。感谢您提供的任何帮助。
答案 0 :(得分:0)
你可以试试这个..
Try
MysqlConn = New MySqlConnection("server=localhost;userid=User;password=******;database=Targets")
MysqlConn.Open()
Dim query as String
query = "INSERT INTO Victims(UserName, Machine, IP) VALUES('" + strUser + "','" + strMachine + "','" + strIPAddress + "')"
Dim cmd As MySqlCommand
cmd = New MySqlCommand(query,MysqlConn)
cmd.ExecuteNonQuery()
MysqlConn.Close()
MessageBox.Show("connected")
Catch ex As MySqlException 的MessageBox.show( “错误”) 结束尝试
答案 1 :(得分:0)
Public Function InsertVal()As Boolean
Dim iReturn As Boolean
Using MysqlConn As New MySqlConnection(connectionString)
Using sqlCommand As New MySqlCommand()
With sqlCommand
.CommandText = "INSERT INTO Victims (UserName, Machine, IP) VALUES(@User,@Machine,@IP)"
.Connection = MysqlConn
.CommandType = CommandType.Text
.Parameters.AddWithValue("@User", lblDisplayUser.Text)
.Parameters.AddWithValue("@Machine", lblDisplayMachine.Text)
.Parameters.AddWithValue("@IP", lblDisplayIP.Text)
End With
Try
MysqlConn.Open()
sqlCommand.ExecuteNonQuery()
iReturn = True
Catch ex As MySqlException
MsgBox(ex.Message.ToString)
iReturn = False
Finally
MysqlConn.Close()
End Try
End Using
End Using
Return InsertVal
这是适合我的解决方案。我不得不将其更改为函数并处理详细的错误消息。谢谢大家的帮助。