繁体   English   中英

使用vb.net将数据插入SQL Server数据库

[英]Insert data into a SQL Server database using vb.net

我创建一个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
Message =')'附近的语法不正确。
Source = .Net SqlClient数据提供程序

堆栈跟踪:

在System.Data.SqlClient.SqlConnection.OnError(SqlException异常,布尔值breakConnection,操作1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action
1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action
1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action
TdsParserStateObject stateObj,布尔值CallerHasConnectionLock,布尔值asyncClose)在System.Data.SqlClient.TdsParser。在System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName,布尔异步,Int32超时,客户端系统数据。 SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1完成,字符串methodName,布尔sendToPipe,Int32超时,布尔&usedCache,布尔asyncWrite,布尔inRetry)位于InventoryManagement.DBSQLServer.insertdata(String qr)中的System.Data.SqlClient.SqlCommand.ExecuteNonQuery() C:\\ Users \\ Joy Alx \\ source \\ repos \\ InventoryManagement \\ InventoryManagement
\\ DBClass \\ DBSQLServer.vb:位于C:\\ Users \\ Joy Alx \\ source \\ repos \\ InventoryManagement \\ InventoryManagement \\ Screens \\ Tools \\ stock.vb的InventoryManagement.stock.Add_Click(Object sender,EventArgs e)的第25行System.Windows.Forms.Control.WmMouseUp(Message&m,MouseButtons button,Int32 clicks)处的Bunifu.Framework.UI.BunifuImageButton.OnClick(EventArgs e)处的System.Windows.Forms.Control.OnClick(EventArgs e)。 System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message.m)在System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&m)在System.Windows.Forms.Windows.Forms.Control.WndProc(Message&m) System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG&msg)处的NativeWindow.DebuggableCallback(IntPtr hWnd,Int32 msg,IntPtr wparam和IntPtr lparam)在System.Windows.Forms.Application.ComponentManager.System.Windows.Forms。 .FPushMessageLoop(IntPtr dwComponentID,Int32原因,Int32 pvLoopData)在System.Windows.Forms.Appl Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()上的System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32原因,ApplicationContext上下文)处的ication.ThreadContext.RunMessageLoopInner(Int32原因,ApplicationContext上下文)。 81行的InventoryManagement.My.MyApplication.Main(String [] Args)的Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String [] commandLine)的WindowsFormsApplicationBase.DoApplicationModel()


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

您的查询有问题:

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字段将失败。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM