How to delete all data in table and insert new records in an Access database with VB.NET? - vb.net

I'm trying to delete all data from a table in an Access (*.mdb) database in VB.NET, then reinsert new data in it however I get the error "Syntax error in INSERT INTO statement" when executing the following code:
Imports System
Imports System.Data
Imports System.Data.SqlClient
...
'test.mdb file
'with a table "MyTable"
'with two fields:
'"name" (Memo), "value" (Memo)
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = C:\Users\Max\Desktop\test.mdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "SELECT * FROM MyTable"
'select data from database, fill and clear dataset to get the table schema
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "MyTable")
ds.Clear()
'add a new row in the dataset
Dim dsNewRow As DataRow = ds.Tables("MyTable").NewRow()
dsNewRow.Item("name") = "TESTNAME"
dsNewRow.Item("value") = "TESTVALUE"
ds.Tables("MyTable").Rows.Add(dsNewRow)
'update the database
Dim objCommandBuilder As New OleDb.OleDbCommandBuilder(da)
da.Update(ds, "MyTable")
ds.Dispose()
da.Dispose()
con.Close()
con.Dispose()

Make a backup copy of your Access db file.
Rename those two fields in MyTable: name to fld1; and value to fld2
Adapt your VB.Net code to use those names.
You indicated those steps eliminated the error.
The problem was that both name and value are reserved words. In some situations, the Access db engine can accept reserved words as field names without complaining. However, it seems less forgiving when OleDb is involved.
Ideally, avoid reserved words for Access db object names. That linked page includes a link to a free utility (DbIssueChecker.zip) you can use to examine your Access db file for problem names and other issues.

Related

How to copy records from one table to another database table with different connection string?

I have two(2) MS Access databases with different connections in different location. Deleting records from the table of the first database is working but inserting new records that was copied from the table of the second database is not working. The table of the first database remains blank. What happened was it was inserted the new records to the table of the second database, that's why the second database have many records because it copied and inserted to itself. What I want is that the copied records from second database will be pasted/inserted to the first database.
SQLStr1 is the location string of the first database
SQLStr2 is the location string of the second databas
Dim conn As OleDbConnection
Dim conn2 As OleDbConnection
Dim cmd As OleDbCommand
Dim cmd2 As OleDbCommand
Dim SQLStr1 As String
Dim SQLStr2 As String
conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=psipop.accdb;Jet OLEDB:Database Password=cscfo13poppsi;")
'I used 'psipop' because the database is located the same with the application.
SQLStr1 = "DELETE * FROM pop 'psipop'"
conn.Open()
cmd = New OleDbCommand(SQLStr1, conn)
cmd.ExecuteNonQuery()
'I used " & TextBox3.Text & " because the textbox3 contains the path of the another database.
conn2 = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= '" & TextBox3.Text & "' ;Jet OLEDB:Database Password=cscfo13poppsi; ")
SQLStr2 = "INSERT INTO pop SELECT * FROM pop IN '" & TextBox3.Text & "'"
conn2.Open()
cmd2 = New OleDbCommand(SQLStr2, conn2)
cmd2.ExecuteNonQuery()
Please help me to this. Thank you.
E.g.
Using sourceConnection As New OleDbConnection("source connection string here"),
destinationConnection As New OleDbConnection("source connection string here"),
insertCommand As New OleDbCommand("INSERT statement here", destinationConnection),
adapter As New OleDbDataAdapter("SELECT statement here", sourceConnection) With {.InsertCommand = insertCommand,
.AcceptChangesDuringFill = False}
Dim table As New DataTable
adapter.Fill(table)
adapter.Update(table)
End Using
That will populate the DataTable from one database and insert the rows into the other. You'll need to configure the insertCommand with appropriate parameters. Take special note of the AcceptChangesDuringFill property, which ensures that all DataRows have a RowState of Added and are therefore ready to be inserted. Without that, all RowState properties will be Unchanged and nothing will get saved.

OLEDB - select Count not working

Find below what I've done so far, but unfortunately it's not working.
Private BS as New BindingSource
Dim ds As New DataSet
' Make the Connection
Using con As New OleDb.OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source = Database1.mdb")
con.Open()
Dim Sql = "SELECT COUNT ([Eventname]) FROM Eventproposal"
Dim da = New OleDb.OleDbDataAdapter(Sql, con)
da.Fill(ds, "Eventproposal")
' Set the Binding Source
bs.DataSource = ds.Tables("Eventproposal")
con.Close()
End Using
TextBox1.DataBindings.Add("Text", bs, "")
Couple things, you should end all SQL Commands to MS Access with ;
Dim Sql = "SELECT COUNT ([Eventname]) FROM Eventproposal;"
And you did not name your column which will give you an error when you attempt to access it by name.
Dim Sql = "SELECT COUNT ([Eventname]) AS Eventname FROM Eventproposal;"
I believe it will give it a name but not what your thinking. Lastly, when you do your binding, you will have to reference the name of the field in the table.
TextBox1.DataBindings.Add("Text", bs, "Eventname")

operator/operand type mismatch when update dbf file

i have a program needs to update data in dbf file. but it keeps appear error 'operator/operand type mismatch'. here is sample code :
Dim con As OleDbConnection = New OleDbConnection("Provider=vfpoledb;Data Source=C:\folder\paytran.dbf;Collating Sequence=machine;")
Try
Dim strSQL As String = "UPDATE paytran.dbf SET workhr = 20 WHERE empno = 102"
Dim cmd As OleDbCommand = New OleDbCommand(strSQL, con)
con.Open()
Dim myDA As OleDbDataAdapter = New OleDbDataAdapter(cmd)
Dim myDataSet As DataSet = New DataSet()
' Using DataAdapter object fill data from database into DataSet object
myDA.Fill(myDataSet, "MyTable")
' Binding DataSet to DataGridView
DGV.DataSource = myDataSet.Tables("MyTable").DefaultView
con.Close()
con = Nothing
Catch ex As Exception
MessageBox.Show(ex.Message, "Error Select Data")
Finally
If con IsNot Nothing Then
con.Close()
End If
End Try
please help me..
Its your connection string. The connection string should only have to point to the PATH where the data files are located, then all the SQL based commands will by default be able to see any .DBF tables IN that path (or forward if subpaths exists).
Data Source=C:\folder
instead of
Data Source=C:\folder\paytran.dbf
So, now if you have 30 tables in the "C:\folder", you can now query from ALL of them as needed.
You need to explicitly open and close the DBF. Try:
Dim strSQL As String = "Use paytran in 0 shared;UPDATE paytran SET workhr = 20 WHERE empno = 102;use in select('paytran')"

Query/Update MS Access Records

I am attempting to populate items into a datagrid and then update them back into the database using 2 buttons (one loads, one will save) and a datagrid on a form. I keep running into "Syntax error (missing operator) in query expression" upon update and I am not sure why. Another question i have is where do my DataAdapter and Dataset need to be dimensioned in memory? Under the class?
'this loads my data from db into datagrid
Dim con As New OleDb.OleDbConnection
Dim sql As String
con.ConnectionString = "Provider=Microsoft.jet.oledb.4.0;data source=dbsrc.mdb"
con.Open()
sql = "SELECT * from [Employee Assignments]"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "Assignments")
con.Close()
DataGridView1.DataSource = ds.Tables("Assignments")
The following code should update my database to reflect changes made in the datagridview
'this will eventually update the datagrid back into the db
Dim cb As New OleDb.OleDbCommandBuilder(da)
Dim con As New OleDb.OleDbConnection
'Dim sql As String
con.ConnectionString = "Provider=Microsoft.jet.oledb.4.0;data source=dbsrc.mdb"
con.Open()
da.Update(ds, "Assignments")
con.Close()
DataGridView1.DataSource = ds.Tables("Assignments")
I read this artcle on msdn - http://msdn.microsoft.com/en-us/library/system.data.common.dataadapter.update.aspx - but it did not seem to help much, I am confused but I believe my problem is not identifying and passing the correct dataset back into the database. How should I deal with the dataset that I pull, modify, and then send back into the DB using the DataAdapter?
When a table contains spaces in its name you should inform the CommandBuilder about this problem
setting the QuotePrefix and QuoteSuffix property to avoid errors
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
The default for these twos is an empty string and thus, when you try to write your changes back to the database, you get a syntax error.

How to determine the id of a data in vb.net?

I'm currently working on an ms access database in vb.net.
And I need a code that can determine which data I am updating in the database. Because when I try to update the data, the previous data is being cloned and it will generate two data(the updated and the previous data), and the program will also generate a random id number for the updated data, which is not good.
Here is my code for the update button:
'update
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("GH").Rows(INC).Item(1) = TextBox13.Text
ds.Tables("GH").Rows(INC).Item(2) = TextBox14.Text
ds.Tables("GH").Rows(INC).Item(3) = TextBox15.Text
da.Update(ds, "GH")
MsgBox("Data updated")
My code for form load:
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\ACCESS DATABASE\search.mdb"
con.Open()
sql = "SELECT * FROM GH"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "GH")
con.Close()
I'm using system.data.oledb namespace
Here are my declarations:
Dim cmd As OleDbCommand
Dim cn As OleDbConnection
Dim dr As OleDbDataReader
Dim ds As New DataSet
Dim con As New OleDb.OleDbConnection
Dim da As OleDb.OleDbDataAdapter
Your question is not clear to me at all, but if you want to find the last ID of an insert, you would usually check the results of "SELECT ##IDENTITY" immediately after the record is inserted.