[英]Insert data into a SQL Server database using vb.net
I create a SQL Server database and I want to add some data in a particular table of that database. 我创建一个SQL Server数据库,并希望在该数据库的特定表中添加一些数据。 I use some textbox to input the data and an add button to complete.
我使用一些文本框输入数据,并使用添加按钮完成操作。 But when I tap the button the whole process was stopped and indicate an error in the DBSQL module which is shown below.
但是,当我点击按钮时,整个过程停止了,并在DBSQL模块中指出了错误,如下所示。
Here's my code: 这是我的代码:
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
The error occurs on this line: 该行发生错误:
i = cmd.ExecuteNonQuery()
The error is: 错误是:
System.Data.SqlClient.SqlException: 'Incorrect syntax near ')'
System.Data.SqlClient.SqlException:'')附近的语法不正确
Here's my add button code: 这是我的添加按钮代码:
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
When I copy the details of that error it shows: 当我复制该错误的详细信息时,它显示:
System.Data.SqlClient.SqlException
System.Data.SqlClient.SqlException
HResult=0x80131904的HResult = 0x80131904
Message=Incorrect syntax near ')'.Message =')'附近的语法不正确。
Source=.Net SqlClient Data ProviderSource = .Net SqlClient数据提供程序
StackTrace:
堆栈跟踪:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action
1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action在System.Data.SqlClient.SqlConnection.OnError(SqlException异常,布尔值breakConnection,操作
1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)
1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at InventoryManagement.DBSQLServer.insertdata(String qr) in C:\\Users\\Joy Alx\\source\\repos\\InventoryManagement\\InventoryManagement
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)
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:line 25 at InventoryManagement.stock.Add_Click(Object sender, EventArgs e) in C:\\Users\\Joy Alx\\source\\repos\\InventoryManagement\\InventoryManagement\\Screens\\Tools\\stock.vb:line 29 at System.Windows.Forms.Control.OnClick(EventArgs e) at Bunifu.Framework.UI.BunifuImageButton.OnClick(EventArgs e) at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Appl
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action\\ 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 ication.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun() at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel() at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine) at InventoryManagement.My.MyApplication.Main(String[] Args) in :line 81
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.
There's issue with your query : 您的查询有问题:
qr = "Insert into tblProductInfo (ProName, ProDesc, ProPrice, ProStock) Values('" & nametext.Text & "','" & descriptiontext.Text & "','" & pricetext.Text & "','" & stocktext.Text & "',)"
Should be 应该
qr = "Insert into tblProductInfo (ProName, ProDesc, ProPrice, ProStock) Values('" & nametext.Text & "','" & descriptiontext.Text & "','" & pricetext.Text & "','" & stocktext.Text & "')"
Imagine SQL query being like this : 想象一下这样的SQL查询:
Insert into tblProductInfo (ProName, ProDesc, ProPrice, ProStock) Values('[name]','[description]','[price]','[stock]',)
and 和
Insert into tblProductInfo (ProName, ProDesc, ProPrice, ProStock) Values('[name]','[description]','[price]','[stock]')
Edit : Also I have to agree with colleagues - use parametarised queries or stored procedures - that would prevent SQL Injection. 编辑:另外,我还必须同意同事的意见-使用参数化查询或存储过程-这将防止SQL注入。 Also make sure that you are validating inputs before pushing them to db - pushing text to int field will fail.
另外,在将输入推送到db之前,请确保您正在验证输入-将文本推送到int字段将失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.