Query/Update MS Access Records - vb.net

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.

Related

Visual Studio Vb.net loaded dataset from oracle query missing or replacing first row of data

I have a vb.net application program that is suppose to query a oracle/labdaq database and load the dataset into a datatable. For some reason the query works fine and there is no exception thrown, however, when I load the data it seems to be missing the first row. I first noticed the issue when I did a query for a single row and it returned zero rows when I checked the datatable's row amount during debugging. I then compared all my data sets to a data miner application straight from the oracle source and i seems to always be missing one, the first, row of data when I use the application.
here is the code... I changed the query string to something else to maintain company privacy
Private Sub CaqOnSQL(strFileDirect As String)
Try
Dim connString As String = ConfigurationManager.ConnectionStrings("CA_Requisition_Attachments.Internal.ConnectionString").ConnectionString
Dim conn As New OracleConnection With {
.ConnectionString = connString
}
Dim strQuerySQL As String = "SELECT * FROM REQUISITIONS " &
"WHERE DATE BETWEEN TO_DATE('12/10/2020','MM/dd/yyyy') AND " &
"TO_DATE('12/14/2020','MM/dd/yyyy') " &
"ORDER BY ID"
conn.Open()
Dim Cmd As New OracleCommand(strQuerySQL, conn) With {
.CommandType = CommandType.Text
}
Dim dr As OracleDataReader = Cmd.ExecuteReader()
dr.read()
Dim dt As New DataTable
dt.TableName = "RESULTS"
dt.Load(dr)
ExcelFileCreation(dt, strFileDirect)
You should remove the line:
dr.read()
The call to Read is what is causing you to skip the first row, when combined with the DataTable Load method.
In addition, I have taken the liberty to make some additional changes to your code for the purposes of Good Practice. When using Database objects like Connection and Command, you should wrap them in Using blocks to ensure the resources are released as soon as possible.
Dim dt As New DataTable()
dt.TableName = "RESULTS"
Using conn As New OracleConnection(connString)
conn.Open()
Dim strQuerySQL As String = "SELECT * FROM REQUISITIONS " &
"WHERE DATE BETWEEN TO_DATE('12/10/2020','MM/dd/yyyy') AND " &
"TO_DATE('12/14/2020','MM/dd/yyyy') " &
"ORDER BY ID"
Using command = New OracleCommand(strQuerySQL , conn)
Using dataReader = command.ExecuteReader()
dt.Load(dataReader)
End Using
End Using
End Using
Note: Be wary of Using blocks when using a DataReaderas you may find the connection is closed when you don't want it to be. In this case, the DataReader is used entirely within this function and is safe to use.

How to insert multiple records at once using DataSet and DataAdapter in vb.net & ms access?

i was trying to insert record from one table to another using Data Set, first here's the code:
Try
Dim ds1 As New DataSet
Dim dbada2 As New OleDbDataAdapter
Dim dbbl2 As New OleDbCommandBuilder
Dim dbcon As OleDbConnection = New OleDbConnection(dbconstring)
dbcon.Open()
Dim cmd1 As OleDbCommand = New OleDbCommand("SELECT InspectionID, ICTDIR, UnitDescription, SizeType, QuantityNo, SerialNo FROM DeliveryInspection WHERE ICTDIR = #ictdir", dbcon)
cmd1.Parameters.AddWithValue("#ictdir", txtRefNo.Text)
Dim dbada1 As New OleDbDataAdapter(cmd1)
ds1.Clear()
dbada1.Fill(ds1)
dbcon.Close()
dbcon.Open()
dbada2 = New OleDbDataAdapter("SELECT * FROM LogSUF", dbcon)
dbada2.Update(ds1)
dbcon.Close()
Catch ex As Exception
MessageBox.Show(ex.ToString, "DBADA 2 Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
here i have 2 DataAdapters, The first one is from the table DeliveryInspection and the second is from LogSUF. both tables have the same Column with the only difference is that LogSUF has no records.
I want to make a system that will insert a record from DeliveryInspection (with the corresponding ICTDIR from the Text Box where the user typed it which is txtRefNo) to the LogSUF. My code doesn't have error but it doesn't work either and i tried some ways to fix this problem. Please help and also is there another way to do this? I'm a beginner.
When you call Update, only the rows with a RowState of Added, Modified or Deleted will be saved. As it stands, all your rows have a RowState of Unchanged, so there's nothing to save.
The solution is to set AcceptChangesDuringFill to False on the first data adapter, before you call Fill. That way, the AcceptChanges method is not called implicitly when you call Fill and each RowState will remain Added, ready for the row to be inserted when you call Update.

How to load data from an SQLite Database query into a textbox?

So I'm making a rota system for a project and I need a textbox to output the contracted hours of the employee that the user currently has selected in the combo box. The problem is, I have no idea how to go about it;
Sub GetContractedHours()
Dim sSql As String
Dim newds As New DataSet
Dim newdt As New DataTable
sSql = "SELECT emp_contractedhours FROM Employee WHERE emp_fn ='" & cboEmpName.Text & "%'"
Dim con As New SQLiteConnection(ConnectionString)
Dim cmd As New SQLiteCommand(sSql, con)
con.Open()
Dim da As New SQLiteDataAdapter(cmd)
da.Fill(newds, "Employee")
newdt = newds.Tables(0)
txtUserAlertHours.DataSource = newdt
con.Close()
End Sub
Please help! :)
You don't need any of that code. Just get all the data in the first place and then bind your ComboBox and your TextBox, e.g.
Dim table As New DataTable
Dim conection As New SQLiteConnection(ConnectionString)
Dim adapter As New SQLiteDataAdapter("SELECT emp_fn, emp_contractedhours FROM Employee", connection)
adapter.Fill(table)
cboEmpName.DisplayMember = "emp_fn"
cboEmpName.DataSource = table
txtUserAlertHours.DataBindings.Add("Text", table, "emp_contractedhours")
The TextBox will then be automatically populated when you make a selection in the ComboBox. That's how data-binding works.
If you do want to query the database each time then you shouldn't use a data adapter at all. You're only retrieving one value and that's exactly what ExecuteScalar is for. Create a command with the appropriate SQL, call ExecuteScalar and assign the result to the Text of your TextBox.
If you really did want to use data-binding with the code you have (which would be silly) then you can bind just as I have demonstrated above. Just note that, if you're going to use a different DataTable each time, you need to remove the old binding first. You can do that most easily by calling Clear on the DataBindings collection, assuming you have not bound any other properties.

Visual Studio - multiple Table to multiple DataGridView with MS Access

how can i populate multiple table into multiple DataGridview?
for example i have 3 tables which is table1, table2 and table3, and in my form i have 3 dataGridView with name of dataGridView1, dataGridView2 and dataGridView3. i found this solution Updating an Access Database via a DataGridView Using OLEDB in VB.NET as a result of my code.
function loadDatabaseDataToGridView
Dim msAccessFilePath As String
Dim con As New OleDbConnection
Dim dataTable, dataTable2, dataTable3, dataTable4 As New DataTable
Dim olebDataAdapter As New OleDbDataAdapter
Dim da As New OleDbDataAdapter
Dim dataSet As New DataSet
Private Sub loadDatabaseDataToGridView()
Try
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & msAccessFilePath
dataSet.Tables.Add(dataTable)
olebDataAdapter = New OleDbDataAdapter("Select * from table1", con)
olebDataAdapter.Fill(dataTable)
olebDataAdapter = New OleDbDataAdapter("Select * from table2", con)
olebDataAdapter.Fill(dataTable2)
olebDataAdapter = New OleDbDataAdapter("Select * from table3", con)
olebDataAdapter.Fill(dataTable3)
DataGridView1.DataSource = dataTable.DefaultView
DataGridView2.DataSource = dataTable2.DefaultView
DataGridView3.DataSource = dataTable3.DefaultView
Dim cb = New OleDbCommandBuilder(olebDataAdapter)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
MessageBox.Show("Successfull")
Catch ex As Exception
MessageBox.Show("Failed")
con.Close()
End Try
con.Close()
End Sub
function SaveChanges
'Perform this on Button Save is Click
Private Sub saveChanges()
olebDataAdapter.Update(dataSet)
End Sub
This code is working as excpected, it is populating the data from MS Access file but when i clicked the button save to save the changes on edited data, an error has occurred.
THE ERROR:
Concurrency violation: the UpdateCommand affected 0 of the expected 1 records
anyone does know how to properly implement of what i am trying to achieve? Thank You Very Much!!!
Each DataAdapter object only has a single UpdateCommand, so you'll need one for each data table. If it runs the update command and no rows are updated (because the update command is actually for a table that you haven't changed) then you'll get the Concurrency Violatation.
It actually gets more complicated than this if your tables are related as the order that inserts, updates and deletions occur can be critical.
If you create a Strongly Typed Dataset it generates designer code that includes a TableAdapterManager class and all of the required data adapters. It might be worth playing around with this just so that you can see how the generated code works.
Just a note, the 'Concurrency violation' exception is actually there so that you can design an update command that will only succeed if the contents of the record in the database match the data held locally (to prevent you from overwriting another user's changes). Search for Optimistic Locking for more details.

How to delete all data in table and insert new records in an Access database with 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.