问题:将数据插入数据库。
错误:
用户未处理SQLException
关键字“用户”
附近的语法不正确
我放箭头的那一行是突出显示的行似乎是我不确定的错误。
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Data.SqlClient
Imports System.Configuration
Partial Public Class _Default
Inherits System.Web.UI.Page
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
con.Open()
End Sub
Protected Sub addBTN_Click(ByVal sender As Object, ByVal e As EventArgs) Handles addBTN.Click
Dim cmd As New SqlCommand("insert into User (Name, Gender, Age) values ('" & nameTB.Text & "', '" & genderTB.Text & "', '" & ageTB.Text & "')", con)
cmd.ExecuteNonQuery() <------------------------------
con.Close()
nameTB.Text = ""
genderTB.Text = ""
ageTB.Text = ""
End Sub
End Class
答案 0 :(得分:2)
用户是保留字,因此需要放在方括号中。您的查询对SQL注入是开放的,因此需要进行参数化。我建议您在需要之前打开连接。另外,使用Using
语句将为您完成关闭和处理。
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
Using cmd As New SqlCommand("insert into [User] (Name, Gender, Age) values (@nameTB, @genderTB,@ageTB)", con)
cmd.Parameters.AddWithValue("@nameTB", nameTB.Text)
cmd.Parameters.AddWithValue("@genderTB", genderTB.Text)
cmd.Parameters.AddWithValue("@ageTB", ageTB.Text)
cmd.CommandType = CommandType.Text
con.Open()
cmd.ExecuteNonQuery()
nameTB.Text = ""
genderTB.Text = ""
ageTB.Text = ""
End Using
End Using
答案 1 :(得分:0)
User
是reserved word。用方括号括起来:
Dim cmd As New SqlCommand("insert into [User] (Name, Gender, Age) values ('" & nameTB.Text & "', '" & genderTB.Text & "', '" & ageTB.Text & "')", con)