我正在尝试使用 vb.net 创建一个调整 MySQL 数据库中数据的函数。
这是我的代码:
Private Sub alterDB_Click(sender As Object, e As EventArgs) Handles alterDB.Click
Dim user As String = globalValue.userN
Dim password As String = globalValue.passwN
If ComboBox1.Text <> "" Then
Dim newValue As Integer
newValue = Label3.Text - NumericUpDown1.Value
Dim conn As New sqlConnection
Dim answerN As DataTable
Dim sqlQnA As String = "INSERT INTO equiptment(inStorage) value '" & newValue & "' WHERE iName='" & ComboBox1.Text & "'"
conn.altering(user, password, sqlQnA)
answerN = conn.getData()
End If
End Sub
我收到的错误消息表明它几乎可以正常工作,只是不完全:)
Error msg: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near "140' WHERE iNavn='SkateboardW15" at line 1.
最佳答案
尝试更新而不是插入。另外,您应该研究参数化查询,以避免 SQL 注入(inject)攻击。你拥有的东西非常脆弱。您似乎正在使用自定义类型来管理连接并执行查询。这很好,但是您需要添加对该类型的查询参数支持。还值得一提的是,ADO.Net 依赖于连接池功能,因此当您对大多数查询使用新的 SqlConnection 对象时,它的效果最佳。
Private Sub alterDB_Click(sender As Object, e As EventArgs) Handles alterDB.Click
'Move password enforcement to your connection object or connection string
'use a guard clause that does not increase the nesting depth of your code
If string.IsNullOrWhiteSpace(ComboBox1.Text) Then Exit Sub
Dim newValue As Integer = CInt(Label3.Text) - NumericUpDown1.Value
'sql string should be a constant, or any changes should only be typed by the programmer
' never the user
Dim sqlQnA As String = "UPDATE equipment SET inStorage = @newValue WHERE iName= @iName"
'Using block will guarantee the connection is closed properly, even if an exception is thrown
Using conn As New SqlConnection("connection string here"), _
cmd As New SqlCommand(sqlQnA, conn)
'use query parameters that allow you to set the specific database type and length you need
cmd.Parameters.Add("@newValue", SqlDbType.Int).Value = newValue
cmd.Parameters.Add("@iName", SqlDbType.NVarChar, 40).Value = ComboBox1.Text
conn.Open()
cmd.ExecuteNonquery()
End Using
End Sub
关于mysql - 用vb.net调整数据库(MySQL)数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23276744/