【问题标题】:Insert data into a SQL Server database using vb.net使用 vb.net 将数据插入 SQL Server 数据库
【发布时间】:2019-11-22 09:57:42
【问题描述】:

我创建了一个 SQL Server 数据库,我想在该数据库的特定表中添加一些数据。我使用一些文本框来输入数据并使用添加按钮来完成。但是当我点击按钮时,整个过程都停止了,并在 DBSQL 模块中显示错误,如下所示。

这是我的代码:

Imports System.Data
Imports System.Data.SqlClient

Module DBSQLServer
    Public con As New SqlConnection("Data Source=JOYALXDESKTOP\SQLEXPRESS;Initial Catalog=SaleInventory;Integrated Security=True")
    Public cmd As New SqlCommand
    Public da As New SqlDataAdapter
    Public ds As New DataSet
    Public dt As DataTable
    Public qr As String
    Public i As Integer

    Public Function searchdata(ByVal qr As String) As DataSet
        da = New SqlDataAdapter(qr, con)
        ds = New DataSet
        da.Fill(ds)
        Return ds

    End Function

    Public Function insertdata(ByVal qr As String) As Integer

        cmd = New SqlCommand(qr, con)
        con.Open()
        i = cmd.ExecuteNonQuery()
        con.Close()
        Return i

    End Function
End Module

错误发生在这一行:

i = cmd.ExecuteNonQuery()

错误是:

System.Data.SqlClient.SqlException: '') 附近的语法不正确'

这是我的添加按钮代码:

Private Sub Add_Click(sender As Object, e As EventArgs) Handles add.Click
        If (isformvalid()) Then
            qr = "Insert into tblProductInfo (ProName, ProDesc, ProPrice, ProStock) Values('" & nametext.Text & "','" & descriptiontext.Text & "','" & pricetext.Text & "','" & stocktext.Text & "',)"
            Dim logincorrect As Boolean = Convert.ToBoolean(insertdata(qr))
            If (logincorrect) Then
                MsgBox("Stock Added Successfully ...", MsgBoxStyle.Information)
            Else
                MsgBox("Something Wrong. Record Not Saved. Please Check and Try Again...", MsgBoxStyle.Critical)
            End If
        End If
    End Sub

当我复制该错误的详细信息时,它会显示:

System.Data.SqlClient.SqlException
HResult=0x80131904
消息=')' 附近的语法不正确。
Source=.Net SqlClient 数据提供者

堆栈跟踪:

在 System.Data.SqlClient.SqlConnection.OnError(SqlException 异常, Boolean breakConnection, Action1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action
1 wrapCloseInAction) 在 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj,布尔调用者HasConnectionLock,布尔异步关闭) 在 System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,SqlCommand cmdHandler,SqlDataReader dataStream,BulkCopySimpleResultSet bulkCopyHandler,TdsParserStateObject stateObj,Boolean & dataReady) 在 System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(字符串方法名,布尔异步,Int32 超时,布尔异步写入) 在 System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 完成,字符串方法名,布尔 sendToPipe,Int32 超时,布尔和 usedCache,布尔异步写入,布尔 inRetry) 在 System.Data.SqlClient.SqlCommand.ExecuteNonQuery() 在 C:\Users\Joy Alx\source\repos\InventoryManagement\InventoryManagement\DBClass\DBSQLServer.vb:line 25 中的 InventoryManagement.DBSQLServer.insertdata(String qr) 在 C:\Users\Joy Alx\source\repos\InventoryManagement\InventoryManagement\Screens\Tools\stock.vb:line 29 中的 InventoryManagement.stock.Add_Click(Object sender, EventArgs e) 在 System.Windows.Forms.Control.OnClick(EventArgs e) 在 Bunifu.Framework.UI.BunifuImageButton.OnClick(EventArgs e) 在 System.Windows.Forms.Control.WmMouseUp(消息和 m,MouseButtons 按钮,Int32 点击) 在 System.Windows.Forms.Control.WndProc(消息和 m) 在 System.Windows.Forms.Control.ControlNativeWindow.OnMessage(消息& m) 在 System.Windows.Forms.Control.ControlNativeWindow.WndProc(消息和 m) 在 System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd,Int32 msg,IntPtr wparam,IntPtr lparam) 在 System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(味精和味精) 在 System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID,Int32 原因,Int32 pvLoopData) 在 System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 原因,ApplicationContext 上下文) 在 System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 原因,ApplicationContext 上下文) 在 Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun() 在 Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel() 在 Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(字符串 [] 命令行) 在 InventoryManagement.My.MyApplication.Main(String[] Args) 中:第 81 行


If I have done anything wrong to ask this type question, I am sorry. I am new in this community.Thanks in advance.

【问题讨论】:

  • <..>& stocktext.Text & "',)" - 注意在右括号前有额外的 ',' 吗?
  • @VytautasPlečkaitis 所说的是您的直接问题。但是,您应该考虑使用参数,因为它可以通过使代码更易于阅读并防止对您的数据库/应用程序的恶意攻击来帮助防止此类错误和许多其他错误
  • 这样的错误来自于阅读构建 SQL 代码的 VB 代码但从未阅读过 SQL 代码的人。如果您被告知您的 SQL 中有语法错误,请查看您的 SQL。
  • 是的,参数化查询或存储过程是要走的路。还要确保数据类型有效 - 例如您没有将字符串推送到 int 或位字段
  • 请注意您使用的产品标签!您的代码适用于 MS SQL Server,而您将问题标记为 MySQL。

标签: sql sql-server vb.net inventory-management


【解决方案1】:

您的查询有问题:

qr = "Insert into tblProductInfo (ProName, ProDesc, ProPrice, ProStock) Values('" & nametext.Text & "','" & descriptiontext.Text & "','" & pricetext.Text & "','" & stocktext.Text & "',)"

应该是

qr = "Insert into tblProductInfo (ProName, ProDesc, ProPrice, ProStock) Values('" & nametext.Text & "','" & descriptiontext.Text & "','" & pricetext.Text & "','" & stocktext.Text & "')"

想象一下 SQL 查询是这样的:

Insert into tblProductInfo (ProName, ProDesc, ProPrice, ProStock) Values('[name]','[description]','[price]','[stock]',)

Insert into tblProductInfo (ProName, ProDesc, ProPrice, ProStock) Values('[name]','[description]','[price]','[stock]')

编辑:我也必须同意同事的意见——使用参数化查询或存储过程——这将防止 SQL 注入。还要确保在将输入推送到 db 之前验证输入 - 将文本推送到 int 字段将失败。

【讨论】:

  • 应该是这样的SqlCommand obj_sqlCommand = new SqlCommand();obj_sqlCommand.CommandType = CommandType.StoredProcedure;
  • 请停止编写继续促进 sql 注入攻击的答案。 thecrazyprogrammer.com/2014/10/…
  • @granadaCoder 我只指出了代码的问题(如导致问题的原因)。我永远不会建议在靠近生产环境的任何地方使用这种方法(即使在私有测试环境中也是如此) - 实际上我会建议完全停止使用 sql 查询(使用实体框架/存储过程/等),但这将完全被淘汰这个问题的范围。我确实提到了有更好/更安全的方法,但那是供 OP 选择、学习和使用的。
  • 我知道..“这解决了你的问题”....但是当问题的提出者没有指出这一点时......他们通常认为“一切都很好”。您的“编辑”是适当的,谢谢。
猜你喜欢
  • 2012-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多