【发布时间】:2019-07-27 15:43:19
【问题描述】:
我创建了一个 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()
在表格中,我有 5 列:
ProID, ProName, ProDesc, ProPrice, ProStock
ProID 是我的主键。
这是我将数据添加到数据库中的添加按钮代码:
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
当我的查询是:
qr = "Insert into tblProductInfo (ProName, ProDesc, ProPrice, ProStock) Values('" & nametext.Text & "','" & descriptiontext.Text & "','" & pricetext.Text & "','" & stocktext.Text & "')"
错误如下:
System.Data.SqlClient.SqlException: '不能将 NULL 值插入到列 'ProID' 表 'SaleInventory.dbo.tblProductInfo' 中;列不允许空值。插入失败。
当我的查询是:
qr = "Insert into tblProductInfo (ProID, ProName, ProDesc, ProPrice, ProStock) Values('" & idtext.Text & "','" & nametext.Text & "','" & descriptiontext.Text & "','" & pricetext.Text & "','" & stocktext.Text & "')" `
那么错误是:
System.Data.SqlClient.SqlException:'违反主键约束'PK_tblProductInfo'。无法在对象“dbo.tblProductInfo”中插入重复键。重复键值为 (1)。
【问题讨论】:
-
您是否忘记将 ProID 列设为自增列?
-
我不确定。我该如何检查?我目前使用的是 Microsoft SQL Server Management Studio。
-
SQL Injection alert - 您应该不将您的 SQL 语句连接在一起 - 使用 参数化查询 来避免 SQL 注入 - 查看 Little Bobby Tables
-
如何检查? 在 SSMS 中右键单击您的表,选择 Design,选择主键行,查看 Column Properties 窗口并验证 Identity Specification 是否包含 Yes 表示 (Is Identity)、1 表示 Identity Seed 和 1 表示 身份增量
-
很高兴能提供帮助,但您应该真正注意@marc_s 评论。永远不要以这种方式编写查询。如果您将十进制值存储在字符串列中,我预计现在价格列会出现问题,反之亦然,如果您在需要十进制值时传递字符串值。了解如何使用参数