how to update empty datatable by the data from another datatable - mysql

I have 2 servers that contain the same databases with the same structure (Main Server + Sub Server).
I deleted all data from the table in the sub server.
I got the data from the table from the main server and put it in Datatable.
I copied the data from the Datatable of the server2.
I use Dataadapter2 to update the table in the sub server.
but still, the sub server is empty?!
'Delete Data From The Sub Server
xSlConn.Open()
Dim xcmddelete As New MySqlCommand("Delete FROM tblplaces", xSlConn)
xcmddelete.ExecuteNonQuery()
'Get Data Drom The Main Server
Conn.Open()
Dim xcmd1 As New MySqlCommand("SELECT * FROM tblplaces", Conn)
Dim xdt1 As New DataTable
Dim xda1 As New MySqlDataAdapter(xcmd1)
xda1.Fill(xdt1)
'Preparing the datatable for the Sub Server
Dim xcmd As New MySqlCommand("SELECT * FROM tblplaces", xSlConn)
Dim xdt2 As New DataTable
Dim xda2 As New MySqlCommand(xcmd)
Dim xB As New MySqlCommandBuilder(xda2)
xda2.Fill(xdt2)
'Copt the data from the main datatable to the sub datatable
xdt2 = xdt1.Copy()
'Update The Datatable2
xB.GetUpdateCommand()
xda2.Update(xdt2)

xda2.Fill(xdt2)
This line of code is useless; the next line of code tosses out xdt2 anyway
xdt2 = xdt1.Copy()
This line duplicates the datatable. It won't set all the rows in xdt2 to be RowState of Added, which is what the datadapter needs them to be in order to run an insert on them
A dataadapter inspects each row's RowState. Unchanged rows are ignored. Added have the INSERT command run on them, Modified maps to UPDATE, Deleted maps to the DELETE query
Right now all the rows in your xdt1 are Unchanged because the dataadapter called AcceptChanges on them after it added them to the table
Now.. you don't need to copy the data at all; you can just set all the rows in xdt1 to be Added so the xdt2 adapter will use its INSERT command on them. Also, it should be possible to just swap the connection out on the insertcommand
'Get Data Drom The Main Server
Dim dt As New DataTable
Dim da As New MySqlDataAdapter("SELECT * FROM tblplaces", Conn)
da.Fill(dt)
Dim xB As New MySqlCommandBuilder(da)
da.InsertCommand.Connection = xSlConn
For Each ro as DataRow in xdt1.Rows
ro.SetAdded()
Next ro
da.Update(dt)
Or, you can simply request that the xda1 adapter NOT call AcceptChanges on them at all, so they will be in Added state already:
'Get Data Drom The Main Server
Dim dt As New DataTable
Dim da As New MySqlDataAdapter("SELECT * FROM tblplaces", Conn)
da.AcceptChangesDuringFill = False
da.Fill(dt)
Dim xB As New MySqlCommandBuilder(da)
da.InsertCommand.Connection = xSlConn
da.Update(dt)
Or if you're pushing to a different db
'Get Data Drom The Main Server
Dim dt As New DataTable
Dim da As New MySqlDataAdapter("SELECT * FROM tblplaces", Conn)
da.AcceptChangesDuringFill = False
da.Fill(dt)
Dim da2 as New SqliteDataAdapter("SELECT * FROM tblplaces", "put a connection string here")
Dim xB As New SqliteCommandBuilder(da2)
da2.Update(dt)
Note; this latter example uses eg SQLite as a demo of declaring two different adapters of different types for different db - it doesn't guarantee that eg the specific SQLite library you're using actually contains a dataadapter implementation (some don't)

First, you need to use Using...End Using blocks to make sure you database objects are disposed. Don't declare database connections and commands outside of the method where they are used.
Your main problem is the Fill method of the DataAdapter sets all rows to unchanged. I changed this to the DataTable.Load method which takes a parameter of LoadOption. This will preserve the RowState Added. Then when you call Update on the DataAdapter the row will be recognized. If the row is Unchanged the DataAdapter will not update the database.
Private ConStrMain As String = "Your Main server connection string"
Private ConStrSub As String = "Your Sub server connection string"
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Delete Data From The Sub Server
Using conSub As New MySqlConnection(ConStrSub),
cmd As New MySqlCommand("Delete FROM tblplaces", conSub)
conSub.Open()
cmd.ExecuteNonQuery()
End Using
'Retrieve data from Main server
Dim dt As New DataTable
Using conMain As New MySqlConnection(ConStrMain),
cmd As New MySqlCommand("SELECT * FROM tblplaces", conMain)
conMain.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader, LoadOption.Upsert)
End Using
End Using
'Insert data from Main to Sub server
Using conSub As New MySqlConnection(ConStrSub),
da As New MySqlDataAdapter("SELECT * FROM tblplaces", conSub)
Dim sb As New MySqlCommandBuilder(da)
da.Update(dt)
End Using
End Sub

Related

There is no row at position 0 Vb.net and Mysql

I'm trying to get and print data from a row "status" on the table "printer" and it keeps saying "There is no row at position 0."
Dim conn As New deepconnection()
Dim adapter As New MySqlDataAdapter()
Dim table As New DataTable()
Dim ds, ds1 As New DataSet
Dim command As New MySqlCommand("SELECT * FROM printer", conn.getConnection)
conn.openOcean()
PrinterStatus.Text = table.Rows(0).Item("status")
The connection:
Private fishcatch As New MySqlConnection("datasource=localhost;port=3306;username=root;password=xxxxx;database=deep_ocean")
' Get the connection only to read
ReadOnly Property getConnection() As MySqlConnection
Get
Return fishcatch
End Get
End Property
Open connection:
Sub openOcean()
If fishcatch.State = ConnectionState.Closed Then
fishcatch.Open()
End If
End Sub
What is wrong?
You haven't executed the command to fill the table. Without that part the table is still empty
Dim command As New MySqlCommand("SELECT * FROM printer", conn.getConnection)
conn.openOcean()
' Execute the command and pass the reader to the table load method
table.Load(command.ExecuteReader())
PrinterStatus.Text = table.Rows(0).Item("status")
Even after this the table could still be empty if there is no record in the database table named Printer, so before reading anything from a datatable check always the rows count
If table.Rows.Count > 0 Then
PrinterStatus.Text = table.Rows(0).Item("status")
...
End If

How properly insert data from dynamic DataTable to MySQL?

Actually i have a method where the user is able to choose data from excel file and choose between some headers name which are set statically and are equals to MySQL columns name in a table, then i just collect that data in a DataTable.
Now i would be able to store that data in MySQL database but which would be the best method to insert that data from a DataTable into MySQL? The rows of DataTable could contain more than 50.000/100.000 items.
That's how the DataTable could look's like (The header is choosen dynamically by the user from a combobox)
So in this Insert method which would be the best way to add that data? Should i just loop throw dataTable items and make multiple inserts?
Private Sub InsertDB()
Dim dataTable = ExcelToDT(TxtUpload.Text, ColumnHeader(PanelColumns, Column))
Dim dbCon As New Odbc.OdbcConnection
Dim conStr As String = "DSN=WRRPT"
dbCon.ConnectionString = conStr
dbCon.Open()
Dim cmd As New Odbc.OdbcCommand
With cmd
.CommandText = "INSERT INTO ? VALUES ?"
.Connection = dbCon
End With
Dim reader As Odbc.OdbcDataReader
reader = cmd.ExecuteReader
dbCon.Close()
reader = Nothing
cmd = Nothing
End Sub

Loop through Database table and get all values of each record in turn

I need to get all the values of each record in a table, this is so I can then add them to a text file log, a record per line, and then delete them from the database. I'm new to this and have searched how to add SQL query results to an array or a generic list, but I don't fully understand them.
All I have so far is:
Private Sub btnClearAll_Click(sender As Object, e As EventArgs) Handles btnClearAll.Click
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Application Programming\Project\Issue Logger\Database\IssueLoggerDB.accdb"
Dim strSQl = "TRUNCATE TABLE CurrentJobs"
Dim commandInsert As New OleDbCommand
commandInsert.CommandText = strSQl
commandInsert.Connection = conn
commandInsert.Connection.Open()
commandInsert.ExecuteNonQuery()
Me.ReportViewer1.RefreshReport()
End Sub
This is for a Uni project, and above is how we have been to shown to do it, however nothing I have found while researching looks similar.
Feel free to use this procedure:
Private Sub DataTableToTextFile()
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Application Programming\Project\Issue Logger\Database\IssueLoggerDB.accdb"
Using conn As OleDbConnection = New OleDbConnection(connString)
Dim dt As New DataTable
conn.Open()
'Change the query. It's not a good practice to use '*' in your select queries. Please, use the column names instead.
Dim dataAdapter As New OleDbDataAdapter("SELECT * FROM CurrentJobs", conn)
dataAdapter.Fill(dt)
'Change the path to your desired path
Dim exportPath As String = "C:\Logs\"
Dim exportFileName As String = "log.txt"
'If directory does not exists, create it
If Not Directory.Exists(exportPath) Then
Directory.CreateDirectory(exportPath)
End If
'Write data into the text file
Dim writer As New StreamWriter(exportPath + exportFileName)
Try
Dim sb As New StringBuilder
For Each row As DataRow In dt.Rows
sb = New StringBuilder
For Each col As DataColumn In dt.Columns
sb.Append(row(col.ColumnName))
Next
writer.WriteLine(sb.ToString())
Next
Catch ex As Exception
Throw ex
Finally
If Not writer Is Nothing Then writer.Close()
End Try
'Finally clean database table
Dim strSQl = "Delete From CurrentJobs"
Dim commandDelete As New OleDbCommand(strSQl, conn)
'execute
commandDelete.ExecuteNonQuery()
'close connection
conn.Close()
End Using
End Sub

How to display data in datagrid from mysql in multiple forms?

I have 2 forms, in the first form the datagrid populates with data in mysql. Then to repeat this for my second form I copied the code over and changed all variable names, but when I load the form the datagrid is not populated with mysql data, it doesn't even throw an error. Here is the code I used for my first form and below is for my second form.
This is the code for the second form, where it doesn't work, the code is exactly the same (changed variable names) for the first form.
Second form:
Public Class frmShareholderDetails
Dim connection As New MySqlConnection
Dim myadapter As New MySqlDataAdapter
Dim mycommandbuilder As MySqlCommandBuilder
Dim mycommand As MySqlCommand
Dim datatable As New DataTable
Dim dataset As New DataSet
Dim mydatagridviewprinter As datagridviewprinter
Dim objconnection As New MySqlConnection("Server=localhost;database=ba-solutions;user id=root;password=")
'declaring variables
Private Sub frmShareholderDetails_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
connection.ConnectionString =
("Server=localhost;database=ba-solutions;user id=root;password=")
Try
connection.Open()
'opens connection
Catch ex As Exception
MsgBox("Cannot connect to BA-Solutions Database")
End Try
myadapter.SelectCommand = New MySqlCommand
myadapter.SelectCommand.Connection = connection
myadapter.SelectCommand.CommandText = "select * from Shareholder_Details"
'creates adapters
mycommandbuilder = New MySqlCommandBuilder(myadapter)
myadapter.Fill(datatable)
myadapter.SelectCommand.CommandType = CommandType.Text
dataset = New DataSet
myadapter.Fill(dataset, "Shareholder_Details")
rowposition = 0
DGVShareholder.DataSource = dataset.Tables("Shareholder_Details")
'sets datasource
connection.Close()
'close connection
Dim recordsondisplay As Integer
recordsondisplay = DGVShareholder.RowCount
lblRecords.Text = recordsondisplay & " records in database."
End Sub
End Class
Can anyone see where the problem lies? I have been using trial and error, but no solution yet.

Get specific row col values from mysql using vb 2012

I have one button retrieve I just want to get the database table "account" value by its row and col and display it in a textbox. I keep on getting errors on the datafill line
Imports MySql.Data.MySqlClient
Public Class Form1
Dim dataset As DataSet
Dim datatable As DataTable
Dim sqlcon As MySqlConnection
Dim dataadapter As MySqlDataAdapter
Dim sqlcommand As MySqlCommand
Dim sql As String
Private Sub retrieve_Click(sender As Object, e As EventArgs) Handles retrieve.Click
sqlcon = New MySqlConnection("Data Source=localhost;Database=database;User ID=root;Password=;")
sqlcon.Open()
sql = "select * from account"
dataadapter = New MySqlDataAdapter(sql, sqlcon)
dataadapter.Fill(dataset)
TextBox2.Text = dataset.Tables(0).Rows(0).Item(0).ToString()
End Sub
End Class
You need to instantiate the dataset that you pass to the Fill method.
....
dataset = new DataSet()
dataadapter.Fill(dataset)
...
Do not forget to close the connection when finished. It is a resource very costly to keep open when you not need it
Using sqlcon = New MySqlConnection("Data Source=localhost;Database=database;User ID=root;Password=;")
sqlcon.Open()
sql = "select * from account"
dataadapter = New MySqlDataAdapter(sql, sqlcon)
dataset = new DataSet()
dataadapter.Fill(dataset)
TextBox2.Text = dataset.Tables(0).Rows(0).Item(0).ToString()
End Using
See the Using Statement
However if you need only one row it is better to refine the query applying a WHERE clause to limit the results returned by the database.
sql = "select * from account WHERE AccountName = #name"
dataadapter = New MySqlDataAdapter(sql, sqlcon)
dataadapter.SelectCommand.Parameters.AddWWithValue("#name", inputNameBox.Text)
dataset = new DataSet()
dataadapter.Fill(dataset, "Account")
if dataset.Tables("Account").Rows.Count > 0 then
TextBox2.Text = dataset.Tables("Account").Rows(0).Item(0).ToString()
End If
this hopefully will return just the row needed