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

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.

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.

Easiest way to update a OleDB table from a DataTable

What's the easiest way (vb.NET) to update a full OleDB table from a previous modified imported table?
Here's what I have.
First I import the table from an Access Database:
Dim PRDB As String = "Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=<location>;
Jet OLEDB:Database Password=<password>"
Dim CNDB As New OleDb.OleDbConnection(PRDB)
Dim CMDB As New OleDb.OleDbCommand
Dim ADDB As New OleDb.OleDbDataAdapter(CMDB)
Dim TBDB As New DataTable
Try : CNDB.Open()
Catch EX As Exception : MsgBox(EX.ToString) : End Try
Try : CMDB.CommandText = "SELECT * FROM [TABLE 01]" : ADDB.Fill(TBDB)
Catch EX As Exception : MsgBox(EX.ToString) : End Try
So far so good. I managed to import TABLE 01 successfully to TBDB.
Now, let's say I change one cell of the DataTable:
TBDB.Rows(2).Item(3) = "CHANGED"
Is there a way to update directly the OleBD table without describing the changed cell adress? Something like
ADDB.Update(TBDB) (?)
I already tried the last bit of code but it didn't work (I think it works only if the argument is a DataRow not a DataTable).
I researched this matter, but all the answers I found looked a lit bit complicated for this (apparent) simple task. So I wonder if there is a more direct way to do this - I also read something about Binders, but I didn't quite understand the method.
Thanks
Thanks to #Fadi, I managed to get the exact method I was looking for using the OleDbCommandBuilder:
Dim CMNDBUID As OleDb.OleDbCommandBuilder
CMNDBUID = New OleDb.OleDbCommandBuilder(ADDB)
CMNDBUID.GetUpdateCommand()
Then I can easily update the Access table:
Try : ADDB.Update(TBDB)
Catch EX As Exception : MsgBox(EX.ToString) : End Try
In SQL SERVER the equivalent is:
Private Sub UpdateDBFromDataTable(myDataTable As DataTable)
'Change with your connection string
Dim connectionString As String = "Data Source = MyServerName/Instance; Integrated Security=true; Initial Catalog=YourDatabase"
Using connection As SqlConnection = New SqlConnection(connectionString)
connection.Open()
Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(connection)
For Each c As DataColumn In myDataTable.Columns
bulkCopy.ColumnMappings.Add(c.ColumnName, c.ColumnName)
Next
'Put here your table name in Database
bulkCopy.DestinationTableName = myDataTable.TableName
Try
bulkCopy.WriteToServer(myDataTable)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Using
End Using
End Sub

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.

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.