输入框中的数据未插入数据库

时间:2014-11-27 10:15:49

标签: asp.net vb.net

我制作此表单以在数据库中插入信息。我不知道错误来自哪里。它没有将输入字段中的信息插入数据库。

这是我的代码:

 Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim id, name, description, code, cat_industry, cat_theme, cat_occasion, cat_budget As String
        id = product_id.Text
        name = product_name.Text
        description = product_description.Text
        code = item_code.Text
        cat_industry = industry.SelectedValue
        cat_theme = theme.SelectedValue
        cat_occasion = occasion.SelectedValue
        cat_budget = budget.SelectedValue

        Try
            Dim str1 As String = "insert into product (ID, Product_Name, Product_Description, Item_Code, Industry, Theme, Occasion, Budget) values ('" + id + "', '" + name + "', '" + description + "', '" + code + "', '" + cat_industry + "', '" + cat_theme + "', '" + cat_occasion + "', '" + cat_budget + "')"
            con.Open()
            Dim cmd As New SqlCommand(str1, con)
            cmd.ExecuteNonQuery()
            con.Close()
        Catch ex As Exception
            Response.Write(ex)
        End Try
    End Sub

1 个答案:

答案 0 :(得分:3)

您的列名称不能被引用为Product NameProduct Description并带有空格 - 您需要将其转义为[Product Name], [Product Description]等。

但请不要直接插入数据 - 而应该是parameterizing输入变量。从性能和安全性(Sql Injection)的角度来看,这都有好处。

 Dim str1 As String = "insert into product (ID, [Product Name], [Product Description], Item_Code, etc) " _
                      " values (@id, @name, @description, @code, etc)"
 con.Open()
 Dim cmd As New SqlCommand(str1, con)
 cmd.Parameters.AddWithValue("@id", id )
 cmd.Parameters.AddWithValue("@name", name )
 ... etc
 cmd.ExecuteNonQuery()
相关问题