我正在尝试从表单视图中获取用户输入的数据并将其插入数据库中的表 问题是,只要编译器到达Rtype变量来存储其值,它就会给我这个错误: 我知道这个错误意味着什么,但我根本无法让它发挥作用。 以下是我在Form1类中的代码
Imports System.Data.SqlClient
Public Class Form1`
Private Sub newBtn_Click(sender As Object, e As EventArgs) Handles BtnNwRoom.Click
Dim obj As New Hotl()
Dim selectedItem As Object
selectedItem = hotelCombobox.SelectedItem()
If (obj.addnew(CInt(Me.roomNum.Text), CInt(selectedItem), Me.roomType.Text, Me.price.Text) = False) Then
MsgBox(" no record is added, Try again later")
End If
End Sub
End class
这是添加新功能:
Public Function addnew(ByVal roomNo As Integer, ByVal hotelNo As String, ByVal RoomType As String, ByVal price As Integer) As Boolean
Dim sqlstmnt = "insert into Room (roomNo,hotelNo,RoomType,price) values( " & roomNo & " , " & hotelNo & " , " & RoomType & " , " & price & ")"
MsgBox(sqlstmnt)
conn = ConNew()
'''''''''''''''''''''''''''''' Execute Reader
''''''''''''''''''''''''''''''''''''''''''''''
Dim command As New SqlCommand(sqlstmnt, conn)
If command.ExecuteNonQuery() = 1 Then
MessageBox.Show("insertion Succeded")
Return True
Else
Return False
End If
End Function
答案 0 :(得分:1)
正如蒂姆所说,改为使用参数化查询。
但是,问题的主要原因在于:
RoomType As String
Dim sqlstmnt = "insert into Room (roomNo,hotelNo,RoomType,price) values( " & roomNo & " , " & hotelNo &
" , " & RoomType & " , " & price & ")"
RoomType被定义为一个字符串,但是在查询中没有包含撇号(因此它将被解释为数字或名称,而不是字符串。
因此,在这种特殊情况下,请使用:
Dim sqlstmnt = "insert into Room (roomNo,hotelNo,RoomType,price) values( " & roomNo & " , " & hotelNo &
" , '" & RoomType & "' , " & price & ")"
但是要强调(除其他事项)安全性的重要性之外,请使用参数化问题,而不是直接在SQL查询中使用原始用户输入。
只是为了澄清一下,这是一个带参数化查询的例子:
Public Function addnew(ByVal roomNo As Integer, ByVal hotelNo As String, ByVal RoomType As String, ByVal price As Integer) As Boolean
Dim sqlstmnt As String = "INSERT INTO ROOM (roomNo,hotelNo,RoomType,price) VALUES(@roomNo, @hotelNo, @RoomType, @price)"
MsgBox(sqlstmnt)
conn = ConNew()
'''''''''''''''''''''''''''''' Execute Reader
''''''''''''''''''''''''''''''''''''''''''''''
Dim command As New SqlCommand(sqlstmnt, conn)
command.Parameters.Add("@roomNo",SqlDbType.Int).Value = roomNo
command.Parameters.Add("@hotelNo",SqlDbType.Int).Value = hotelNo
command.Parameters.Add("@RoomType",SqlDbType.NVarChar,50).Value = RoomType
command.Parameters.Add("@price",SqlDbType.Int).Value = price
If command.ExecuteNonQuery() = 1 Then
MessageBox.Show("insertion Succeded")
Return True
Else
Return False
End If
End Function
使用此代码,您可以防止SQL注入,并且不会因使用保留字等而遇到不可预见的问题。