Insert into OLEDB VB.NET

大憨熊 提交于 2019-12-10 12:24:20

问题


What is wrong with this?

da.InsertCommand = New OleDb.OleDbCommand("Insert Into Table1 Values( 1, '" & TextBox1.Text & "')")
da.InsertCommand.Connection = con
con.Open()
da.Update(ds)
con.Close()

The database is never updated no matter what. Or is there a better way to insert into db? I have tried the CommandBuilder but it doesnt seem to work as well. Or can I directly execute a query on my database in VB.NET?


回答1:


You are a bit confused regarding on what DataAdapter.Update does. The Update works applying your InsertCommand, UpdateCommand, DeleteCommand to every Added, Modified or Deleted rows present in your DataSource (supposing ds is a DataSet).
It doesn't add/delete/update a record to the database by itself.

If you want to add a record to the database you should write (pseudo)code like this

Using con = GetConnection()
Using cmd = new con.CreateCommand()
    cmd.CommandText = "Insert Into Table1 Values( 1, ?)"
    cmd.Parameters.AddWithValue("@param1", textbox1.Text)
    cmd.Connection = con
    con.Open()
    cmd.ExecuteNonQuery()
End Using
End Using

Note the use of the Using statement to be sure of closing and disposing the connection and the command. Also, never concatenate strings to build sql commands. Using parameters avoid parsing problems and SQLInjection attacks.

EDIT: Based on your comment below and supposing that the first column of the Table1 is an autonumber field you could change the code in this way

Using con = GetConnection()
Using cmd = new con.CreateCommand()
    cmd.CommandText = "Insert Into Table1 Values(?)"
    cmd.Parameters.AddWithValue("@param1", textbox1.Text)
    cmd.Connection = con
    con.Open()
    cmd.ExecuteNonQuery()
End Using
End Using

Also, for the problem for 'nothing has been added' I think you have the database file (mdb) included in your project and the property Copy To The Output Directory set to Copy Always

See a detailed explanation on MSDN at this page




回答2:


Yes, its because you havent tried to run your non-query. Remember, SELECT statement is a query statement while INSERT, UPDATE, DELETE are non-query statement. da.Update() or da.Fill() will only pull result from a query operation.

You need to add an extra line after you open the connection as da.ExecuteNonQuery() or any statement that executes a non-query statement in VB.NET!

~Shakir Shabbir




回答3:


Neat and tidy...

Using oCmd As New OleDbCommand("Insert Into Table1 Values(1, '" & TextBox1.Text & "')", con)
    oCmd.ExecuteNonQuery()
End Using

It's a bit nasty because of the possibility of SQL Injection or Textbox1.Text containing single quotes but for test/dev purposes it'll work.



来源:https://stackoverflow.com/questions/13932095/insert-into-oledb-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!