我正在尝试在Access数据库中插入数据但得到Syntax error
例外:(我做错了什么?
Private Sub savebtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles savebtn.Click
Dim con As OleDb.OleDbConnection = New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\vb8\Mini-project\Mini-project\mini_db.mdb")
Dim query As String
Try
con.Open()
query = "INSERT INTO minitab VALUES (" & TextBox1.Text & "," & TextBox2.Text & ",@dob ," & TextBox5.Text & "," & TextBox6.Text & "," & TextBox7.Text & "," & TextBox8.Text & "," & TextBox9.Text & ")"
Dim da As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(query, con)
Dim dt As New DataTable
da.Fill(dt)
MsgBox("Data has been saved", MsgBoxStyle.SystemModal, "ok")
Catch ex As Exception
MsgBox(ex.Message)
End Try
con.Close()
End Sub
答案 0 :(得分:1)
您正在Insert
语句中添加值而不对列进行寻址。现在,如果您按正确顺序放置值,则不需要这样做,因此我建议您再次检查它。但是,如果您指定了列名,那么你的insert语句可能如下所示:
"INSERT INTO minitab(column1,Column2,Column3)VALUES(@col1,@col2,@col3)",connectiontring
cmd.Parameters.Add("@col1",OleDbType.VarChar).Value = TxtBox1.Text 'make sure to set the datatype correctly
cmd.Parameters.Add("@col2",OleDbType.VarChar).Value = TxtBox2.Text
.........
cmd.ExecuteNonQuery
最重要的是,你想做什么?如果您要插入数据,那么为什么使用DataTable
?上面的代码将允许您将数据插入数据库。但是,数据表用于从数据库中获取数据并显示它。同时DataTable
具有更改跟踪,并与DataAdapters
一起用于执行CRUD操作。
但是,要使用DataTable
显示数据,您可以尝试:
Dim cmd as new OleDbCommand("Select * from minitab",connectionstring)
Dim dt as new DataTable
Dim ada as new OleDbDataAdapter(cmd)
ada.Fill(dt)
要显示数据,您可以使用各种控件。其中一个是DataGridView
。
DataGridView1.DataSource = dt
希望你明白:)