INSERT INTO语句Visual Basic中的语法错误

时间:2014-03-03 16:25:51

标签: vb.net

我不知道是否已经回答了这个问题,但我在insert into语句中遇到语法错误问题。 继承我的代码,我正在使用visual basic 2010,并将ms access 2010作为我的数据库

Imports System.Data.OleDb
Imports Comprehensive.Form1
Public Class Form2
Dim cnn As New OleDb.OleDbConnection
Private Sub RefreshData()
    If Not cnn.State = ConnectionState.Open Then
        cnn.Open()
    End If
    Dim da As New OleDb.OleDbDataAdapter("SELECT * FROM items ORDER BY ID", cnn)
    Dim dt As New DataTable
    da.Fill(dt)
    Form1.DataGridView1.DataSource = dt
    cnn.Close()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim cmd As New OleDbCommand
    Try
        If Not cnn.State = ConnectionState.Open Then
            cnn.Open()
        End If


        cmd.Connection = cnn
        cmd.CommandText = "INSERT INTO Items (Item_Name, Item_Type, Date_Added)" + "'VALUES('" & TextBox1.Text  & "','" & TextBox2.Text & "','" & TextBox3.Text & "');'"
        cmd.ExecuteNonQuery()
        RefreshData()
    Catch ex As Exception
        MessageBox.Show(ex.Message & " - " & ex.Source)
        cnn.Close()
    End Try



End Sub

Private Sub Form2_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    'TODO: This line of code loads data into the 'ShitdataDataSet.Items' table. You can move, or remove it, as needed.
    Me.ItemsTableAdapter.Fill(Me.ShitdataDataSet.Items)
    cnn = New OleDb.OleDbConnection
    cnn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=shitdata.mdb;"
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    Me.Close()
End Sub

结束班

1 个答案:

答案 0 :(得分:1)

INSERT行包含在VALUES关键字AND之前不需要的单引号在sql语句的末尾,删除它们

 (Item_Name, Item_Type, Date_Added) VALUES(....) 
                                  ^^^          ^^^

但是像往常一样,你不会以这种方式编写sql命令 您应该始终使用参数化查询(SQL Injections

    cmd.Connection = cnn
    cmd.CommandText = "INSERT INTO Items (Item_Name, Item_Type, Date_Added)" & _
                      "VALUES(?, ?, ?)"
    cmd.Parameters.AddWithValue("@p1", TextBox1.Text)
    cmd.Parameters.AddWithValue("@p2", TextBox2.Text)
    cmd.Parameters.AddWithValue("@p3", TextBox3.Text)
    cmd.ExecuteNonQuery()

并且,作为最后一点,请记住,如果您的表中有一个日期时间(应该如此),那么您需要将textbox3值转换为日期时间。

如果是这种情况,那么,我建议查看this question已解决在访问数据库中插入日期时间值的问题。