update computer from mysql server - mysql

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

Related

How to open connection simultaneously with multiple connection?

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

VBA Connection Issue with MySQL - Connected at Top of Macro, but not bottom

I have a macro that opens an ADODB connection to a MySQL library. There are two queries that are generated in the macro. The first, which works, is a select statement to check for duplicates. The second, which is not working, is to insert records onto the same table the select statement referenced. I am receiving no errors from VBA, and when I copy/paste directly into MySQL the query works fine.
At the top of my macro I set up the connection as follows:
TimesheetConn = "DRIVER={MySQL ODBC 5.3 ANSI Driver}; SERVER=*server number*;PORT=*port number*;database=my_db;UID=User;PWD=password;Option=2"
'Connection Info
Dim cnn As ADODB.Connection
On Error GoTo AdoError
Set cnn = New ADODB.Connection
With cnn
.ConnectionString = TimesheetConn
.Open
.CommandTimeout = 0
End With
Set FIT_Data = New ADODB.Recordset
Set Task_Data = New ADODB.Recordset
I then develop the Select query (fitidquery) and run it as:
FIT_Data.Open fitidquery, cnn, CursorType = 2
I do not close the connection, but then move on to generate my next query, an insert query (addtasks3), by looping through rows and assigning variables.
Then I try to call the connection again with:
Task_Data.Open addtasks3, cnn, adOpenForwardOnly, adLockReadOnly
cnn.Close
And it doesn't work, nor does it give me any errors either for VBA or SQL. As said before, copying the result of debug.print(addtasks3) into MySQL the query runs correctly and inserts the records.
I've tried opening a 2nd connection with the same parameters. That didn't work as well. I moved the On Error language down to in front of the second query call and it moves on to the AdoError message which seems to indicate that the connection is lost there.
I appreciate any help!
If you issue an Insert-statement, there is no need to involve a recordset. You can simply execute
cnn.Execute addtasks3
Or, if you want to get the number of rows you inserted, use a ADODB.Command:
Dim cmd As New ADODB.Command
cmd.ActiveConnection = cnn
cmd.CommandText = addtasks3
Dim rowsInserted As Long
Call cmd.Execute(rowsInserted)
Debug.Print rowsInserted & " rows inserted."
So I have to say thank you to all of you that mentioned On Errors. Your descriptions after rereading finally made it click with me what I did. I had thought that On Error Resume Next only worked for the line it was in front of in the code (I am still very much a VBA newbie learning as I go) and didn't realize that it would follow through the rest of the code. I had one before my first query because if its a new row it wouldn't return anything to check a duplicate against and cause an error. Hence why I wasn't getting error messages.
I added "On Error GoTo 0" after that section and now I'm getting error messages again. Turns out my user is denied use of the Insert Command for that table (even though I modeled it after a table where it does have use), so it looks like I just need to figure that out. Thank you everyone!

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.

Error updating MySQL database: DUPLICATE DEFAULT ENTRY FOR PRIMARY KEY = '0'

I have a MySQL dsetup called in-out and I have written a vb.NET client program to get information from the table in the database, display it in a data grid view, and then allow to user to edit this information and update it on the server.
Right now I am hosting the server on my Gateway laptop and also connecting to it from the same laptop therefore I'm using localhost as the server name. My problem is that when I go into the program and change the information and click update, nothing happens... The information stays the same yet there is no sign of an error, syntax failure, or program crash.
I've tried running this on another computer in my house and I get the same results. I can access the information without a hitch but updating it is where I run into trouble. If there was a problem with my code it would have displayed some sort of error or asked me to debug my script, which would have made it a lot easier to solve, therefore I am certain that it has something to do with my database.
Before I got to this step, I kept getting an error when retrieving the information that said something like
DUPLICATE DEFAULT ENTRY FOR PRIMARY KEY = '0'
Which means that the columns in the table related to this error cannot have more than one default value of '0', but that's gone now... (Even though I didn't change anything)
Here is the script that will recreate my database layout. Just run it in MySQL WorkBench or MySQL Query Browser (or what ever your using to manage your SQL Database).
Here's my update code: (just in case the problem lies in my program not the database)
Private Sub cmdupdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdupdate.Click
Dim conn As New MySqlConnection
Dim myCommand As New MySqlCommand
'#######
conn.ConnectionString = "server=" & frmLogin.txtserver.Text & ";" _
& "user id=" & frmLogin.txtusername.Text & ";" _
& "password=" & frmLogin.txtpassword.Text & ";" _
& "database=in_out"
'#######
myCommand.Connection = conn
myCommand.CommandText = "INSERT INTO event(user_id, message_id, timestamp, status, creator)" _
& "VALUES(?UserID, ?MessageID, NOW(), ?Status, ?Creator)"
myCommand.Parameters.AddWithValue("?UserID", myUserID)
myCommand.Parameters.AddWithValue("?MessageID", cbomessage.SelectedValue)
myCommand.Parameters.AddWithValue("?Status", cbostatus.SelectedItem)
myCommand.Parameters.AddWithValue("?Creator", myUserID)
Try
conn.Open()
myCommand.ExecuteNonQuery()
Catch myerror As MySqlException
MsgBox("There was an error updating the database: " & myerror.Message)
End Try
refreshStatus(dgvstatus)
End Sub
Additional Details:
OS: Windows 7 Professional x64
Software: Visual Basic 2010 Express
Server Name: 'Localhost'
SQL Manager: MySQL Workbench 5.2.34 CE
Seems that you have some sort of transaction problem going on...
try to add myCommand.Connection.Close(); after the ExecuteNonQuery()
EDIT - as per comment:
Some links to learn SQL:
http://www.w3schools.com/sql/default.asp
http://www.sqlcourse.com/index.html
http://www.sql-tutorial.net/
http://www.mysqltutorial.org/
EDIT 2:
UPDATE event SET
timestamp = NOW(),
status = ?Status
WHERE user_id = ?UserID AND message_id = ?MessageID AND creator = ?Creator;
Since there is not enough details about the data model the above UPDATE statement assumes that the columns user_id and message_id and creator together identify a row uniquely... and update the timestamp and status columns accordingly...

How do I establish a connection to MySQL via VB & display simple query results on a form?

I have a project in Visual Studio 2008 and there is a working data connection to a MySQL database. In other words, I can query the db directly from Visual Studio and it will display the results.
I've tried a couple of approaches that I found online for writing a connection string and accessing the db, but no luck yet.
All I'm trying to do is code a button to query the db and then reset the text property of a label/textbox to display the results based upon another label/textbox value.
The pseudo-code I am imagining is something like this:
Private Sub query_submit_button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles query_submit_button.Click
result_textbox.Text = SELECT field FROM table WHERE otherfield = key_textbox.Text
End Sub
I didn't see any related questions posted on SO - forgive me if I missed one that already exists and this is a dupe.
What is the correct way to accomplish this?
EDIT
Using MySQL 5.1
You can download the ODBC Provider and then reference, import, and use it to query the database through a ODBCCommand instance.
'Put this at the very top of your .VB file...
Imports System.Data.ODBC
'Put this in some method in your code when you are ready to query the DB...
Using connection As New OdbcConnection(connectionString)
Dim command As New OdbcCommand(strSqlQuery, connection)
connection.Open()
result_textbox.Text = command.ExecuteScalar.ToString
End Using
i used DaMartyr's answer to get 99% there, but needed to add this declaration:
Dim connectionString As String = "driver={MySQL ODBC 5.1 Driver};server=SERVER;uid=USERID;pwd=PASSWORD;database=DATABASE"
just replace the SERVER, USERID, PASSWORD, & DATABASE with your personal settings