Public Sub SaveNames(ByRef SQLStatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
.ExecuteNonQuery()
End With
SQLConnection.Close()
MsgBox("succesfully added")
SQLConnection.Dispose()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cmd As MySqlCommand = New MySqlCommand
Dim SQLStatement As String
SQLStatement = "INSERT INTO pres(name) VALUES('" & txtPres.Text & "') "
SQLStatement &= "INSERT INTO vpres(vname) VALUES('" & txtVice.Text & "') "
SaveNames(SQLStatement)
cmd.CommandText = SQLStatement
End Sub
这是我的代码,当我运行这个代码时,它运行顺畅,但是当我保存记录时,我在公共子上得到.ExecuteNonQuery()错误。
这就是它所说的
您的SQL语法有错误;查看与您的MySQL服务器版本对应的手册,以便在第1行的“INSERT INTO vpres(vname)VALUES('aaa')'附近使用正确的语法
答案 0 :(得分:1)
您可以像这样使用它们。确保使用;
结束语句。当语法结束时,DELIMITER
告诉MySQL。
Dim SQLStatement As String
SQLStatement = "INSERT INTO pres(name) VALUES('" & txtPres.Text & "');"
SQLStatement = SQLStatment + "INSERT INTO vpres(vname) VALUES('" & txtVice.Text & "');"
SaveNames(SQLStatement)
cmd.CommandText = SQLStatement
为了获得额外的安全保障,您应该将'
替换为''
Dim SQLStatement As String
SQLStatement = "INSERT INTO pres(name) VALUES('" & Replace(txtPres.Text,"'","''") & "');"
SQLStatement = SQLStatment + "INSERT INTO vpres(vname) VALUES('" & Replace(txtVice.Text,"'","''") & "');"
SaveNames(SQLStatement)
cmd.CommandText = SQLStatement
此外,您的按钮事件包含不需要的代码。
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim SQLStatement As String
SQLStatement = "INSERT INTO pres(name) VALUES('" & txtPres.Text & "') "
SQLStatement = SQLStatment + "INSERT INTO vpres(vname) VALUES('" & txtVice.Text & "') "
SaveNames(SQLStatement)
End Sub
所有数据库内容都发生在SaveNames
。
答案 1 :(得分:0)
您可以使用文本框值对SQL注入开放。你最好使用参数化的sql。
但是试试......
Dim SQLStatement As String
SQLStatement = "INSERT INTO pres(name) VALUES('" & txtPres.Text & "'); "
SQLStatement += "INSERT INTO vpres(vname) VALUES('" & txtVice.Text & "'); "
SaveNames(SQLStatement)
但最好还是试试......
Dim SQLStatement As New StringBuilder
SQLStatement.Append("INSERT INTO pres(name) VALUES('").Append(txtPres.Text).Append("'); ")
SQLStatement.Append("INSERT INTO vpres(vname) VALUES('").Append(txtVice.Text).Append("'); ")
SaveNames(SQLStatement.ToString)