You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决VB.NET中的SQL语法错误?请求技术协助

嘿,我来帮你搞定这个MySQL插入的问题!先看看你的代码里几个关键的坑:

问题分析与修复方案

1. 保留关键字冲突

change是MySQL的保留关键字,直接把它当字段名用会触发语法错误。解决办法是用反引号把这个字段名括起来,告诉MySQL这是个普通字段:

INSERT into fishshop.recordsale (name,itemuse,description,price,qty,total,amount,`change`) ...

2. 用错了执行方法

INSERT是数据写入操作,不需要返回结果集,你用ExecuteReader()就错了——这个方法是用来读取查询结果的。应该换成ExecuteNonQuery(),它专门用来执行增删改这类不返回结果的语句。

3. 致命的SQL注入风险

你直接把TextBox的内容拼进SQL语句里,不仅容易因为用户输入单引号这类特殊字符导致报错,还会给SQL注入攻击留后门,这是非常危险的操作。必须改用参数化查询,把用户输入作为参数传递,而不是直接拼接。

修复后的完整代码

Dim query As String = "INSERT into fishshop.recordsale (name,itemuse,description,price,qty,total,amount,`change`) " & _
                      "VALUES(@name, @itemuse, @description, @price, @qty, @total, @amount, @change)"

Using Command As New MySqlCommand(query, Moduleconn.conn)
    ' 给每个字段绑定参数,注意参数类型要和数据库字段匹配,这里可以根据你的实际字段类型调整
    Command.Parameters.AddWithValue("@name", TextBox2.Text)
    Command.Parameters.AddWithValue("@itemuse", TextBox3.Text)
    Command.Parameters.AddWithValue("@description", TextBox5.Text)
    Command.Parameters.AddWithValue("@price", TextBox4.Text)
    Command.Parameters.AddWithValue("@qty", TextBox6.Text)
    Command.Parameters.AddWithValue("@total", TextBox7.Text)
    Command.Parameters.AddWithValue("@amount", TextBox9.Text)
    Command.Parameters.AddWithValue("@change", TextBox10.Text)

    Try
        ' 执行插入操作
        Command.ExecuteNonQuery()
        MsgBox("Transaction Successfully Saved", MsgBoxStyle.Information, "Message")
    Catch ex As MySqlException
        ' 捕获错误信息,方便你调试
        MsgBox($"Error saving transaction: {ex.Message}", MsgBoxStyle.Critical, "Error")
    Finally
        ' 确保连接只在打开状态下才关闭,避免重复关闭报错
        If Moduleconn.conn.State = ConnectionState.Open Then
            Moduleconn.conn.Close()
        End If
    End Try
End Using

额外小建议

  • 尽量别直接关闭全局连接(Moduleconn.conn),如果这个连接还被其他功能复用,关闭后会导致其他操作失败。最好用Using语句管理连接生命周期,或者确认只有当前操作在使用它时再关闭。
  • 像price、qty、total这类数值型字段,别直接传字符串,最好先把TextBox的内容转换成对应的数值类型(比如Decimal.Parse(TextBox4.Text))再传入参数,避免类型转换错误。

内容的提问来源于stack exchange,提问作者Kyle Jebb Bahala

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:31:45