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

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.

Related

Visual Basic, Copying Success but does not Insert data into SQL TABLE

I have some problems here. I need help.
Recently, I have created a local database called stock.mdf and the application will be getting all the data from the hosting MySQL database into this local SQL Server database.
I am using sqlBulkCopy to inserting all the data. I have tried to view it after inserting. But when I close my application, I head back to check the table data. It does not inserted. Why is that?
Here is my code:
Here will be retrieving the data from the hosting
Dim connStr As String = "server=xxxx;user=xxx;database=xxx;password=xxxx;"
Dim conn As New MySqlConnection(connStr)
Dim cmd As New MySqlCommand
Dim Adapter As New MySqlDataAdapter
Dim StockData As New DataTable
Try
Dim SQL As String = "SELECT * FROM stock"
Console.WriteLine("Connecting to MYSQL.....")
conn.Open()
cmd.Connection = conn
cmd.CommandText = SQL
Adapter.SelectCommand = cmd
Adapter.Fill(StockData)
' StockViewGrid.DataSource = StockData
Catch ex As Exception
Console.WriteLine(ex.ToString())
Finally
conn.Close()
Console.Write("Done")
End Try
This will be the places where sqlBulkCopy working:
As well, I am trying to view from the stock table.
Dim Local_connectionStr As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|stock.mdf;Integrated Security=True"
Dim Local_conn As New SqlConnection(Local_connectionStr)
Dim Local_cmd As New SqlCommand
Dim Local_Adapter As New SqlDataAdapter
Dim Local_StockData As New DataTable
Try
Using sqlBulkCopy As New SqlBulkCopy(Local_conn)
'Set the database table name
sqlBulkCopy.DestinationTableName = "stock"
'[OPTIONAL]: Map the DataTable columns with that of the database table
sqlBulkCopy.ColumnMappings.Add("stockId", "stockId")
sqlBulkCopy.ColumnMappings.Add("id_android", "id_android")
sqlBulkCopy.ColumnMappings.Add("itemCode", "itemCode")
sqlBulkCopy.ColumnMappings.Add("quantity", "quantity")
Local_conn.Open()
sqlBulkCopy.WriteToServer(StockData)
Local_conn.Close()
End Using
Catch ex As Exception
Console.WriteLine(ex.ToString())
Finally
Local_conn.Close()
Console.Write("Done")
End Try
Try
Dim SQL As String = "SELECT * FROM stock"
Console.WriteLine("Connecting to MYSQL.....")
Local_conn.Open()
Local_cmd.Connection = Local_conn
Local_cmd.CommandText = SQL
Local_Adapter.SelectCommand = Local_cmd
Local_Adapter.Fill(Local_StockData)
StockViewGrid.DataSource = Local_StockData
Catch ex As Exception
Console.WriteLine(ex.ToString())
Finally
Local_conn.Close()
Console.Write("Done")
End Try
Since I can't comment (not enough points) I will put my thoughts here. Can you check that you got the expected data with a
Console.WriteLine(StockData.Rows.Count.ToString)
Console.ReadLine()
Also, your destination table doesn't have a PK that is auto increment, does it?
Sorry about the comment as an answer. (Untested code)
Unfortunately your code extracts are lacking headers etc, so are not complete, and I cannot be absolutely certain, BUT in your retrieving routine you seem to be declaring StockData as a local variable. This means that, although this may well be being filled with the data from MySQL, it is immediately discarded on exiting from this routine. Therefore the StockData variable in the sqlBulkCopy routine will be empty, and therefore will insert nothing. You need to fix your scope and make sure that the StockData read from MySQL is the same StockData used in SqlBulkCopy.

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.

Refresh DataGridView after executing SQL Command?

Here is my code:
cn.Open()
cmd.CommandText = "insert into Student values('" ......
cmd.ExecuteNonQuery()
cn.Close()
After closing the connection I want my DataGridView to refresh it's data's also.
I am new in VB.NET I tried datagridview.refresh() but it's not working as I think it's like repainting not updating it's data's.
Thanks.
If you update the underlying business object, the UI should update automatically. My guess it that you forgot to do data binding, for example DataGridView.DataSource = yourDataTable.
EDIT: the easiest way from where you are right now would probably be to replace this:
cmd.ExecuteNonQuery()
with this:
Dim dt As New DataTable
dt.Load(cmd.ExecuteReader())
and then:
DataGridView.DataSource = dt
If you need database updates, you may want to use a DataAdapter and its Update method. The overload I linked is specifically for a DataTable, i.e. you don't need a DataSet, unless you have it already.
As #Neolisk said you have to do databinding .. for example
Dim ds as DataSet
Dim sSql As New OleDb.OleDbCommand
sSql = cnEZApp.CreateCommand()
cmd = New Data.OleDb.OleDbDataAdapter("SELECT * FROM student ORDER by kode", conn)
cmd.Fill(ds, "student")
dgvGuru.DataSource = ds.Tables("student")
So, to update table as datasource you have to do
sSql.CommandText = "insert into Student(...) values(...)"
cmd.UpdateCommand = sSql
cmd.UpdateCommand.ExecuteNonQuery()
cmd.ExecuteNonQuery()

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 link ms-access with vb.net

hello sir with this post i m sending my code enter code here
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Info.accdb")
Dim CommandStringX As String = "SELECT * FROM Table1"
Dim myadapter As New OleDbDataAdapter(CommandStringX, conn)
Dim cmdbuilderX = New OleDbCommandBuilder(myadapter)
myadapter.SelectCommand = New OleDbCommand(CommandStringX, conn)
myadapter.InsertCommand = cmdbuilderX.GetInsertCommand
myadapter.UpdateCommand = cmdbuilderX.GetUpdateCommand 'not needed now
myadapter.DeleteCommand = cmdbuilderX.GetDeleteCommand 'not needed now
myadapter.Fill(dtset)
Try
conn.Open()
myadapter.FillSchema(dtset, SchemaType.Mapped) 'make your dataset tables like the ones in your Access database
dtset.Tables("Table1").Rows(0)("Phone Number") = txtPhoneNumber.Text
dtset.Tables("Table1").Rows(0)("Message") = txtMsg.Text
myadapter.Update(dtset) 'Update Access database based on dtset
Catch ex As OleDbException
MsgBox(ex.ToString)
Finally
conn.Close()
End Try
MY problem is that i hav created database and it is empty with specific colums defined by me but there is no data after defining that columns ... i want to store data at runtime so when i execute that it shows me an error like this " null refernce exception was unhandled " at this line
dtset.Tables("Table1").Rows(0)("Phone Number") = txtPhoneNumber.Text
Please help regarding this
You need to execute a sql insert statement to push data into your tables.
If there's no data in the table, then there's no row to access. Thus, the object which is not set in that line is Rows(0). You can't reference the first row in the collection if there are no rows to reference.
It looks like what you're trying to do is add a row to Table1 in your DataSet. Here's some information on how to do that. Essentially, the steps are:
Create a new DataRow using the schema present in the DataTable.
Populate that row with data.
Add that row to the Rows collection in the DataTable.