如何使用查询将数据插入数据库

时间:2014-01-31 14:49:28

标签: vb.net listview textbox

所以我有这个代码,但它得到一个错误的语法错误..我不知道什么是错的任何人都可以帮助我?我是VB的新手。编程

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


    Try
        Dim SqlQuery = "INSERT INTO sample (FirstName,MiddleName,LastName,Gender,age,Year Level,Date of birth,Date Enrolled,Citezenship,Religion,Address,Telephone NO,Average Grade,Father,Fathers Occupation,Fathers Address,Mother,Mothers Occupation,Mothers Address,Guardian,Guardians Address,Family Income,Payed Amount,Balance) VALUES ('" & txtfname.Text & "','" & txtmname.Text & "','" & txtlname.Text & "','" & combosex.Text & "','" & comboage.Text & "','" & comboyear.Text & "','" & txtdateofbirth.Text & "','" & txtdateenrolling.Text & "','" & txtcitezen.Text & "','" & txtreligion.Text & "','" & txtstudentadd.Text & "','" & txtnumber.Text & "','" & txtgrade.Text & "','" & txtfather.Text & "','" & txtfatherocc.Text & "','" & txtfatheradd.Text & "','" & txtmother.Text & "','" & txtmotherocc.Text & "','" & txtmotheradd.Text & "','" & txtguardian.Text & "','" & txtguardianadd.Text & "','" & txtincome.Text & "','" & txtpayment.Text & "','" & TextBox2.Text & "')"
        Dim sqlcommand As New OleDbCommand
        With sqlcommand
            .CommandText = SqlQuery
            .Connection = conn
            .ExecuteNonQuery()
        End With
        MsgBox("one record succesfull added")

    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
End Sub

2 个答案:

答案 0 :(得分:1)

由于您正在公开的SQL注入漏洞,这很可能是。请注意您是如何处理用户输入的:

"... VALUES ('" & txtfname.Text & "', ..."

这可能看起来就像你只是在查询中放入一个数据值,但你实际在做的是将用户输入视为可执行代码。任何带有数据库保留字符的用户输入都会导致问题。例如,如果输入值具有单引号(例如短语"don't use SQL injectable code"),那么您正在构建的结果查询是:

"... VALUES ('don't use SQL injectable code', ..."

当然这会导致语法错误,因为字符串文字后面有t,这是无效的SQL。

不将用户输入视为可执行代码,而是将其视为数据值。使用SQL参数将这些值添加到查询中。像这样:

' replace each concatenated string with a parameter placeholder:
Dim SqlQuery = "... VALUES (@fname, ..."

Dim sqlcommand As New OleDbCommand
With sqlcommand
    .CommandText = SqlQuery
    .Connection = conn

    ' add a parameter for each placeholder:
    .Parameters.AddWithValue("@fname", txtfname.Text)

    .ExecuteNonQuery()
End With

答案 1 :(得分:0)

在没有看到异常消息的情况下,它很难说出了什么是错误的......但是我猜你会说你正在插入数据库期望整数或日期的数据。 您需要以每个字段所需的类型转换数据。

您也可以使用sql注入。尽量使你的数据不完整。