无法在数据库(Access)VB.NET中插入数据

时间:2015-03-14 19:03:01

标签: database vb.net ms-access-2010

我正在研究一个项目。我们的系统是酒店预订。在VB中,它表示它已添加到我的数据库中

但是当我检查我的数据库时没有。 问题是什么 顺便说一下这里是代码: 公共类注册表

Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click

    qry = "INSERT INTO tblGuest(GuestName, Gender, Address)VALUES('" &
    txtName.Text & "','" &
    txtGender.Text & "','" &
    txtAddress.Text & "');"

    cmd = New OleDb.OleDbCommand(qry, con)
    dr = cmd.ExecuteReader()

    MsgBox("Succesfully added in database")

    RoomInfoForm.Show()
End Sub
Private Sub RegistrationForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    koneksyon()
End Sub

结束班

1 个答案:

答案 0 :(得分:1)

仅仅因为你的MsgBox触发并不意味着查询完成​​了你的期望。 这更像是你想要做的事情:

Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click

    'parameterize the query to avoid SQL injection attacks which is the #1 code vulnerability on OWASP Top 10
    Dim qry As String = "INSERT INTO tblGuest(GuestName, Gender, Address)VALUES(?, ?, ?);"

    'Put disposable resources within Using blocks
    Using con As New OleDb.OleDbConnection()
        Using cmd As New OleDb.OleDbCommand(qry, con)

            'Create the parameters.
            Dim paramName As New OleDb.OleDbParameter("@p1", OleDb.OleDbType.VarChar)
            paramName.Value = txtName.Text 'you should null check and validate all these textbox values

            Dim paramGender As New OleDb.OleDbParameter("@p2", OleDb.OleDbType.VarChar)
            paramGender.Value = txtGender.Text

            Dim paramAddress As New OleDb.OleDbParameter("@p3", OleDb.OleDbType.VarChar)
            paramAddress.Value = txtAddress.Text

            'Assign the parameters to the command
            cmd.Parameters.Add(paramName)
            cmd.Parameters.Add(paramGender)
            cmd.Parameters.Add(paramAddress)

            'you are not returning a result set from the command, so ExecuteNonQuery
            cmd.ExecuteNonQuery()

        End Using
    End Using

    MsgBox("Succesfully added in database")

    RoomInfoForm.Show()
End Sub