Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

Cant insert data in database (Access) VB.NET

Im working on a project. Our system is Hotel Reservation. In VB it says that it added in my database

but then when I check my database there is none. What is the problem btw Here's the code: Public Class RegistrationForm

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

End Class

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just because your MsgBox fires doesn't mean the query did what you expect. This is more like what you want to do:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...