VB.NET application unable to run on other computer - mysql

I can debug my project with no errors, but when I build it and copy the executable application to another computer, the application is not running at all. The form does not even appear on screen.
(Here) is the screenshot of my error.
Here is my source code.
Imports System.Data.SqlClient
Imports MySql.Data.MySqlClient
Public Class Form1
Dim MySQLConnection = New MySqlConnection
Dim Command As New MySqlCommand
Dim MyAdapter As New MySqlDataAdapter
Dim sqlCommand As New MySqlCommand
Dim str_carSql As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim response As Boolean = False
Button1.Enabled = False
Try
response = My.Computer.Network.Ping("www.db4free.net")
Label2.Text = "ONLINE"
Label2.ForeColor = Color.Green
Button1.Enabled = True
Catch ex As Exception
Label2.Text = "OFFLINE"
Label2.ForeColor = Color.Red
MsgBox("No internet connection!", MsgBoxStyle.Critical)
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.Cursor = Cursors.WaitCursor
Try
MySQLConnection.ConnectionString = "server=db4free.net ;port=3306; user=prav5ef; password=prav5eF; database=databasetest;"
MySQLConnection.Open()
MsgBox("Connected to server!")
Catch ex As Exception
MsgBox("Failed connecting to server!", MsgBoxStyle.Critical)
End Try
Try
str_carSql = "insert into databasetest (id,name,password) values (#id,#name,#password)"
sqlCommand.Connection = MySQLConnection
sqlCommand.CommandText = str_carSql
sqlCommand.Parameters.AddWithValue("#id", TextBox1.Text)
sqlCommand.Parameters.AddWithValue("#name", TextBox2.Text)
sqlCommand.Parameters.AddWithValue("#password", TextBox3.Text)
sqlCommand.ExecuteNonQuery()
Catch ex As Exception
MsgBox("ID existed: Could not insert record")
End Try
MsgBox("Done")
Application.Restart()
End Sub
End Class
Here is how the application suppose to show :
And the online database that I am using is db4free.net :

Since you did not provide enough information on the error, these are the following problems you might be experiencing, and the solutions to said problems:
A.) Your client may not be running the correct .NET framework for your Program. In which case, install the correct .NET Framework by downloading it here.
B.) You did not include the mysl.data.dll on the client unit. In which case, download the .dll from here and install it in the client unit.

Related

VB.NET function return error and exit sub

I have this connection function in my VB.NET project
Public Function OpenMysqlCon() As MySqlConnection
Dim mMysqlconnection = New MySqlConnection()
Try
Dim strconDB As String = "server='192.168.100.2'; database='mydb';Port=3306; UID='epb'; password='hahaha'; pooling=true"
mMysqlconnection = New MySqlConnection
mMysqlconnection.ConnectionString = strconDB
mMysqlconnection.Open()
OpenMysqlCon = mMysqlconnection
Catch exceptionThatICaught As System.Exception
OpenMysqlCon = Nothing
End Try
End Function
And i will call the function in my VB project something like
Private Sub frmTest_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Using Con=OpenMysqlCon()
'mycode here
End Using
End Sub
However when the connection is not available, it will throw an exception.
How can i avoid the exception by giving a msgbox something like connection not available at the moment, please try again later and then exit the sub that was using the function?
End Sub
The best approach is to not hold the connection in a field of the form but to create and initalize it wherever you need it. The connection-pooling will ensure that no physical connection needs to be created.
So don't use a OpenMysqlCon method at all but code like this(GetAllUsers is just an example):
Public Function GetAllUsers() As List(Of User)
Dim userList = New List(Of User)
Try
Using mMysqlconnection = New MySqlConnection("server='192.168.100.2'; database='mydb';Port=3306; UID='epb'; password='hahaha'; pooling=true")
mMysqlconnection.Open()
Using command = New MySqlCommand("SELECT * FROM USER ORDER By UserName", mMysqlconnection)
Using rdr = command.ExecuteReader()
While rdr.Read()
Dim user = New User()
user.UserName = rdr.GetString(0)
userList.Add(user)
End While
End Using
End Using
End Using
Catch exceptionThatICaught As System.Exception
MessageBox.Show("meaningful message here, logging would be useful too")
Return Nothing
End Try
Return userList
End Function
Maybe helpful because related(you're also reusing the connection): ExecuteReader requires an open and available Connection. The connection's current state is Connecting
It will be something like this.
Public Function OpenMysqlCon() As MySqlConnection
Dim mMysqlconnection As MySqlConnection()
Try
Dim strconDB As String = "server='192.168.100.2'; database='mydb';Port=3306; UID='epb'; password='hahaha'; pooling=true"
mMysqlconnection = New MySqlConnection
mMysqlconnection.ConnectionString = strconDB
mMysqlconnection.Open()
Catch exceptionThatICaught As System.Exception
mMysqlconnection = Nothing
End Try
Return mMysqlconnection
End Function
Private Sub frmTest_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As MySqlConnection = OpenMysqlCon
If con Is Nothing Then
MessageBox.Show("connection not available at the moment, please try again later")
'Me.Close 'uncomment if the app should end
End If
End Sub
edit - this is not tested
Using con As MySqlConnection = OpenMysqlCon
If con Is Nothing Then
MessageBox.Show("connection not available at the moment, please try again later")
'Me.Close 'uncomment if the app should end
Else
'your code
End If
End Using

key word not supported 'data source'

im having problem in my connection. the error said that key word not supported in the data source and i dont what to do next. thanks in advance!
Imports MySql.Data
Imports MySql.Data.MySqlClient
Public Class frmMasancayClinicSignupvb
Dim connection As New MySqlConnection
Dim myReader As MySqlDataReader
Dim Adapter As MySqlDataAdapter
Dim myCommand As MySqlCommand
Dim Dset As New DataSet
Dim table As New DataTable
Dim MyQuery As String
Dim i As Integer
Private Sub frmMasancayClinicSignupvb_Load(sender As Object, e As EventArgs) Handles MyBase.Load
connection = New MySqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mark\Documents\MASANCAYCLINICLOGIN.mdf;Integrated Security=True;Connect Timeout=30")
Try
If connection.State = ConnectionState.Closed Then
connection.Open()
MsgBox("connected to database")
Else
connection.Close()
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
connection.Close()
End Sub
End Class
It appears that you're passing in the arguments for a SqlConnectionStringBuilder - that's for Microsoft's SqlServer database, not MySql. (see
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.integratedsecurity(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2 ).
MySqlConnection takes "Data Source" but doesn't take those other parameters. See :
http://dev.mysql.com/doc/refman/5.0/es/connector-net-examples-mysqlconnection.html#connector-net-examples-mysqlconnection-defctor

Access to MySQL after closing connection

I have a problem with access to my datebase MySQL after closing it. I use Windows Form and MySql Connector from MySql official website to connect to datebase. I use MySQL in XAMPP.
If I open my connection I can do a simple query. But when I close a connection I can still do this query. Why?
Here is my code:
Imports MySql.Data.MySqlClient
Public Class Form1
Dim polaczenieMySql As New MySqlConnection
Dim mySQL As PolaczenieMySQL
Public Sub New()
InitializeComponent()
mySQL = New PolaczenieMySQL(Me)
End Sub
Private Sub btnPolaczMySQL_Click(sender As Object, e As EventArgs) Handles btnPolaczMySQL.Click
mySQL.Polacz()
End Sub
Private Sub RozlaczMySQL_Click(sender As Object, e As EventArgs) Handles btnRozlaczMySQL.Click
mySQL.Rozlacz()
End Sub
Private Sub btnZapytanie_Click(sender As Object, e As EventArgs) Handles btnZapytanieMySQL.Click
Dim zapytanie As String = "SELECT title, price, book_id from books"
mySQL.WykonajZapytanie(zapytanie)
End Sub
End Class
And my connection class:
Imports MySql.Data.MySqlClient
Public Class PolaczenieMySQL
Dim polaczenie As MySqlConnection = New MySqlConnection()
Dim glowneOkno As Form1
Public Sub New(form As Form1)
glowneOkno = form
End Sub
Public Sub Polacz()
polaczenie.ConnectionString = ("server=localhost;user id=root;password=;database=test")
Try
polaczenie.Open()
MessageBox.Show("Połączono z bazą danych MySQL.")
glowneOkno.labelPolaczenieMySQL.Text = "Połączono"
glowneOkno.labelPolaczenieMySQL.ForeColor = Color.Green
Catch myerror As MySqlException
MessageBox.Show("Nie udało się połączyć z bazą danych MySQL: " & myerror.Message)
End Try
End Sub
Public Sub Rozlacz()
Try
polaczenie.Close()
MessageBox.Show("Rozłączono z bazy danych MySQL.")
glowneOkno.labelPolaczenieMySQL.Text = "Nie połączono"
glowneOkno.labelPolaczenieMySQL.ForeColor = Color.Red
Catch myerror As MySqlException
MessageBox.Show("Błąd rozłączenia z bazy danych MySQL: " & myerror.Message)
Finally
polaczenie.Dispose()
End Try
End Sub
Public Sub WykonajZapytanie(ByVal zapytanie As String)
Dim SDA As New MySqlDataAdapter
Dim dbDataSet As New DataTable
Dim bSource As New BindingSource
Try
Dim komenda As MySqlCommand = New MySqlCommand(zapytanie, polaczenie)
SDA.SelectCommand = komenda
SDA.Fill(dbDataSet)
bSource.DataSource = dbDataSet
glowneOkno.DataGridViewMySQL.DataSource = bSource
SDA.Update(dbDataSet)
Catch ex As MySqlException
MessageBox.Show("Nie jesteś połączony z bazą")
End Try
End Sub
End Class
As I said before, after closing connection (mySQL.Rozlacz()) I can still do a query (mySQL.WykonajZapytanie(zapytanie)). What is wrong with this?
PS. Sorry for my polish names
If you look at the docs about the DbDataAdapter you could read this remark
The Fill method retrieves the data from the data source using a SELECT
statement. The IDbConnection object associated with the select command
must be valid, but it does not need to be open. If the IDbConnection
is closed before Fill is called, it is opened to retrieve data and
then closed. If the connection is open before Fill is called, it
remains open.
The MySqlDataAdapter inherits from the DbDataAdapter and there is no override of the Fill method, so it is the inherited class (DbDataAdapter) that works with the associated command, reopening the closed connection and then closing it.
EDIT
You asked also how to avoid this behavior, well you could add a boolean property to your class PolaczenieMySQL that maintains the state of your MySqlConnection
Private _isDead As Boolean
Public Property IsDead() As Boolean
Get
Return _isDead
End Get
Private Set(ByVal value As String)
_isDead = value
End Set
End Property
Now you could set this property to False when you open the connection and True when you close it.
Then check its value before executing the WykonajZapytanie sub
Public Sub WykonajZapytanie(ByVal zapytanie As String)
Dim SDA As New MySqlDataAdapter
Dim dbDataSet As New DataTable
Dim bSource As New BindingSource
if Me.IsDead Then
Throw new Exception("Invalid usage of this class")
End If
......
End Sub
Notice that there is a simpler check using the MySqlConnection property State
if polaczenie.State <> ConnectionState.Open Then
......
but, given the fact that in your Rozlacz method you dispose the connection I suggest to implement the first workaround.
Finally, I really think that you should change the whole pattern of usage. The connection should be opened, used and closed in the same method where it is required. Your actual infrastructure render this impossible. It is better to get rid of the Polacz and Rozlacz and use the mentioned pattern without the need of a global variable for the connection.

PC denied acces to connect to Database

Hi im relatively new to VB.NET so please bear with me here.
Im trying to setup a DB connection to my localhost everything looks good in my code except I get the error, when running the program, this PC is not allowed to connect to this DB, as you can see in the following image:
Here is my code I use to connect to the DB
Imports MySql.Data.MySqlClient
Public Class sreg
Dim ServerString As String = "Server=localhost;User Id=root;Password="";Database=vbdb"
Dim SqlConnection As MySqlConnection = New MySqlConnection
Private Sub sreg_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim SqlConnection As MySqlConnection = New MySqlConnection
SqlConnection.ConnectionString = ServerString
Try
If SQLConnection.State = ConnectionState.Closed Then
SQLConnection.Open()
MsgBox("Successfully connected to MySQL DB")
Else
SQLConnection.Close()
MsgBox("Connection is Closed")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Public Sub SaveNames(ByRef SQLStatment As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLStatment
.CommandType = CommandType.Text
.Connection = SqlConnection
.ExecuteNonQuery()
End With
SqlConnection.Close()
MsgBox("Succesfully Added!")
SqLConnection.dispose()
End Sub
End Class
I suspect the problem might be in this line SqlConnection.ConnectionString = ServerString since above line returns error when I run the program, however when I remove it I get it to work, but get the not allowed to connect to DB error, as you can see in the image
It looks like you are trying to connect to a MySQL server and it looks like the connection string you need is slightly different than for a MSSQL server:
"Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;"
Source: https://www.connectionstrings.com/mysql/

Host x is not allowed to connect to this mysql server

I am trying to make a simple registration & activation system using my mysql server and vb.net and I am using the code below:
Imports MySql.Data.MySqlClient
Public Class ActivateMe
Dim MysqlConn As MySqlConnection
Dim myAdapter As New MySqlDataAdapter
Dim myData As MySqlDataReader
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MysqlConn = New MySqlConnection()
Try
MysqlConn.Open()
Dim checkUsername As String = "SELECT COUNT(*) FROM users WHERE verif=#p1 and username=#p2"
Dim insertData As String = "INSERT INTO users(hasVerif) VALUES(#p3)"
Using MysqlConn = New MySqlConnection(mysqlconntxt4reg)
Using myCommand = New MySqlCommand(checkUsername, MysqlConn)
MysqlConn.Open()
myCommand.Parameters.AddWithValue("#p1", TextBox1.Text)
myCommand.Parameters.AddWithValue("#p2", currentRegUser)
Dim result = myCommand.ExecuteScalar()
If result IsNot Nothing AndAlso Convert.ToInt32(result) > 0 Then
Using myCommand2 = New MySqlCommand(insertData, MysqlConn)
myCommand.Parameters.AddWithValue("#p3", 1)
myCommand2.ExecuteNonQuery()
MsgBox("Successfully Activated! You May Now Login!", MsgBoxStyle.Information, "Success")
Me.Close()
End Using
Else
MsgBox("Invalid Activation Code", MsgBoxStyle.Critical, "Error")
End If
End Using
End Using
MysqlConn.Close()
Catch myerror As MySqlException
MessageBox.Show("Cannot connect to database: " & vbNewLine & vbNewLine & myerror.Message)
Finally
MysqlConn.Dispose()
End Try
End Sub
End Class
The program sends the activation code to the email successfully and uploads the activation code to the database for checking but when I am on the activation form and enter the code, it says:
Host (my pc name) is not allowed to connect to this mysql server
In the different forms, the server accepts the connection and allows access to the database so I don't see why it would be different here...
Please send me help!
Thanks
rodit
I'm not very familiar with MySQL under .NET but I believe you do something a bit odd here. First you open a connection without a connection string (I assume that uses default parameters)
MysqlConn = New MySqlConnection()
Try
MysqlConn.Open()
and then you open another connection using an explicit string
Using MysqlConn = New MySqlConnection(mysqlconntxt4reg)
Using myCommand = New MySqlCommand(checkUsername, MysqlConn)
MysqlConn.Open()
Notice it's the same MysqlConn variable (with different objects).
So the MySqlException you're catching could be coming from any one of them. You can use that exception to find out which of the open calls actually triggered the exception (I assume it's first one).
You should probably also cleanup code and keep only one open call.
Andrei