将数据插入数据库(sqlexception)不起作用

Inserting data into database (sqlexception) not working

我正在尝试从表单视图中获取用户输入的数据并将其插入到数据库中的 table 问题是,每当编译器到达 Rtype 变量来存储它的值时,它都会给我这个错误: 我知道错误的含义,但我就是无法让它工作。 下面是我的代码在classForm1

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

正如蒂姆所说,改用参数化查询。

但是,您的问题的主要原因在这里:

 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 注入,并且不必 运行 因使用保留字等而陷入不可预见的问题