How to open connection simultaneously with multiple connection? - mysql

How do I change connection and execute some query in my form load during run time? it's more like opening multiple connections simultaneously but how do I do that?
Example of the Database info:
EDIT: I do have the Query but I don't know how to open the other connection during run time. the structure of their database is the same so there's no problem when executing the query. The problem is just how do I change the connection during runtime without pressing anything.

Based on #jmcilhinney answer in an external forum. The adapter is using one connection for the Select and another connection for the Insert. The trick is setting the .AcceptChangesDuringFill to False The default changes the Added to Unchanged.
Private Sub UpdateADifferentDatabase()
Using cnSource As New MySqlConnection("First connection string"), cnDestination As New MySqlConnection("Second connection string")
Using selectCommand As New MySqlCommand("Select statement here", cnSource), insertCommand As New MySqlCommand("Insert statement here ", cnDestination)
Using da As New MySqlDataAdapter()
da.SelectCommand = selectCommand
da.InsertCommand = insertCommand
'The following allows the .DataRowState to remain as Added (normally it is changed to Unchanged by the .Fill method)
da.AcceptChangesDuringFill = False
Dim dt As New DataTable
da.Fill(dt)
da.Update(dt)
End Using
End Using
End Using
End Sub

Related

failed to load database information. error in file temp xxxxxxxxxx

Dim dt As New DataTable
With dt
.Columns.Add("Itemname")
.Columns.Add("Quantity")
.Columns.Add("Price")
.Columns.Add("Total")
End With
For Each dr As DataGridViewRow In Me.DataGridView1.Rows
dt.Rows.Add(dr.Cells("Itemname").Value, dr.Cells("Quantity").Value, dr.Cells("Price").Value, dr.Cells("Total").Value)
Next
Dim rptdoc As CrystalDecisions.CrystalReports.Engine.ReportDocument
rptdoc = New ordersprint
rptdoc.SetDataSource(dt)
can somebody help me with this ? here's my code in printing the data in datagridview ?
Failed to load database is when your VB.net is not able to connect to database itself. The query execution comes later. Check if connection string is proper and MySQL db is able to listen to connection request from outside localhost.

update computer from mysql server

I have been working on this for hours I am sure it is something simple I am missing. I have a remote server that gets updated form from another pc once the sever gets updated I would like my PC to get the changes from the server I cant seem to get it done the closest I have been is shown below any help would be greatly appreciated. Connection string no issue just trying to update the PC database to Match the server database
Sub updateRecord()
Try
Dim dbConnection As New MySqlConnection("server=" & My.Settings.ServerIPAddress & ";user id=root;password=T#ttleT#le102;persistsecurityinfo=True;database=pmdatabase")
dbConnection.Open()
Using Adapter As New MySqlDataAdapter("Select * From tblpmdata", dbConnection)
Using Table As New DataTable
Adapter.Fill(Table) 'test to see if table is correct
Adapter.Fill(Me.PmdatabaseDataSet.tblpmdata)
Me.PmdatabaseDataSet.AcceptChanges()
Me.TableAdapterManager.UpdateAll(Me.PmdatabaseDataSet)
MsgBox(Table.Rows.Count)only shows 5 records when the server has 8 records
End Using
End Using
dbConnection.Close()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub

VB.net "There is already an open DataReader associated with this Connection which must be closed first." when entering Visual Studio Debug

My boyfriend and I have spent the last 2 hours trying to get this to work, we have tried putting all the data connections into try's, changing the the connections to gloabal's but whatever we do we end up back at the same problem. The page will load fine when loaded via localhost, but when we try to get in via debug it hits this error.
If we put the code that fails into a try it goes through each connection and then will load, but each part will have been caught in the catch.
An exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll but was not handled in user code
There is already an open DataReader associated with this Connection which must be closed first.
Here's the code, each sub or function that uses MySQL connection has a close in the same as this function. We are out of ideas to what it causing it, as only does it we try and enter debug in Visual Studio.
Public Function getID()
Dim cmd As New MySqlCommand()
Dim reader As MySqlDataReader
Dim rtr As Integer
cmd.CommandText = "MySQLSTATEMENT"
cmd.Connection = CON_STRING
Connection.Open()
reader = cmd.ExecuteReader
If (reader.HasRows()) Then
reader.Read()
rowID = reader.Item(0)
End If
Connection.Close()
reader.Close()
cmd.Dispose()
End Function
You Should Close reader first and then you can close the connection.
I would recommend Using Statement for connection that will take care of closings the connection.

The changes made in mysql database dosent reflect in the vb.net application

I am a beginner in vb and mysql... I am working on a project (vb 2010 express and mysql5.1) where there are two machines in a lan network. The application is installed on both the machines and the database is on one of the machines. Both connect to the DB using same user,(dr_admin). My problem is that the changes made from one machine doesn't get reflected in the other machine.
DBCon = New ADODB.Connection
DBCon.ConnectionString = ("Driver={MySQL ODBC 3.51 Driver};Server=Admin-PC; Database=dr_db; User=dr_admin;Password=dradmin;pooling=false;Option=3;")
DBCon.Open()
MsgBox(DBCon.State)
Try
Cmd = New ADODB.Command
Cmd.ActiveConnection = DBCon
Cmd.CommandText = "SEt autocommit=0;"
Cmd.Execute()
This is how i connect and i manually commit and rollback wherever needed.
I populate a list from the DB. The list is present on a panel. The data is loaded every time the panel becomes visible.
But the new data doesn't show up.
Then i added a bit of code to close current db connection and reopen again.
Public Sub reconnect_pr()
DBCon.Close()
MsgBox(DBCon.State)
DBCon = Nothing
DBCon = New ADODB.Connection
DBCon.ConnectionString = ("Driver={MySQL ODBC 3.51 Driver};Server=Admin-PC;Database=dr_db; User=dr_admin;Password=dradmin;pooling=false;Option=3;")
DBCon.Open()
MsgBox(DBCon.State)
Try
Cmd = New ADODB.Command
Cmd.ActiveConnection = DBCon
Cmd.CommandText = "SEt autocommit=0;"
Cmd.Execute()
Catch ex As Exception
MsgBox("autocommit error - Contact admin", MsgBoxStyle.OkOnly, "Patient Care")
End Try
End Sub
this is the code i use to retrieve the data from db.
Cmd = New ADODB.Command
Cmd.ActiveConnection = login_frm.DBCon
Cmd.CommandText = "select pat_no,pat_id,pat_name from pat_token_details order by pat_no;"
Rs = Cmd.Execute
exp_tod_pat_list.Items.Clear()
exp_tod_pat_list.Items.Add("None")
Do While Not Rs.EOF
v_token = Rs("pat_no").Value
v_pat_name = Rs("pat_name").Value
v_id = Rs("pat_id").Value
exp_tod_pat_list.Items.Add("Token id: " + v_token + " - " + v_pat_name + " ( " + v_id + " )")
Rs.MoveNext()
Loop
Catch ex As Exception
MsgBox("unable to fetch current token details", MsgBoxStyle.OkOnly, "Token")
End Try
Still it doesn't work.. But it gets reflected when i close the application and open it again.
Kindly help me understand the problem.
Thanks.
A short explanation of a reason of this behaviour:
In MySql the default isolation level is REPEATABLE READ.
In this mode (see this link for details: click me):
All consistent reads within the same transaction read the snapshot established by the first read. This convention means that if you issue several plain (nonlocking) SELECT statements within the same transaction, these SELECT statements are consistent also with respect to each other.
In easy words: if you issue, within the same transaction, the same SELECT statement several times, you will always get the same results, regardless of changes of database made by other sessions.
The session remembers, that the first SELECT within the transaction was run at the time X and "makes the snapshot of data" at the time X, then all subsequent selects will read this snaphshot at time X, but not current data.
See next link: (click me):
If the transaction isolation level is REPEATABLE READ (the default level), all consistent reads within the same transaction read the snapshot established by the first such read in that transaction. You can get a fresher snapshot for your queries by committing the current transaction and after that issuing new queries.
By commiting the transaction (or issuing a rollback of the transaction), you end this transaction, and a next SELECT (within a new transaction) will see fresh data.
If auto_commit is enabled, then all selects are always automatically commited - so you always see fresh data. But if you disable auto-commit, in repeatable-read (default) isolaton level, you must commit manually to see changes in the database.
Note: the above behaviour is true only for InnoDb tables. Other engines don't support ACID.

Let the client create his/her own custom MySQL query to get data from the database in vb.net

I want a program that lets the user create his/her own query to retrieve data from the database. What is the best method to achieve such task? Any links or sample code would be much appreciated. Thank you.
I would go for :
Create a form, name it formSample
add a textbox, name it txbSample
add a datagridview, name it dgvSample
add a button, name it btnSample
txbSample will be used by the client to input queries
btnSample is where you would put the code.
dgvSample is the data, not really recommended but it's just used to show the data you have retrieved.
assuming you have connected to the database, the code on btnSample should look like
NOTE: not a complete code
Dim sql As String
sql = txbSample.text
Using cmd As New MySqlCommand
Try
'open the connection here
cmd.Connection = con
cmd.CommandText = sql
Dim dt As New DataTable
da = New MySqlDataAdapter(cmd)
da.Fill(dt)
'close the connection here
dgvSample.DataSource = dt
Catch ex As Exception
MessageBox.Show("Error while fetching data.")
'close the connection here
End Try
End Using
dt is a datatable where the data are stored. You should do something to be able to use it:)