MySQL Connection code needs fixing. I hit a dead end - mysql

I'm currently working on a custom admin panel for a DayZ server, which will run on a local computer & connect to a remote database. I've Google'd more than ever, but I've hit a dead end. I can't seem to find a fix for this code which I've found & been told that it should work.
Public Function sqlConnect(ByVal server, port, instance, uname, pword) As Boolean
Dim connection As SqlConnection
connection = New SqlConnection()
connection.ConnectionString = "Server=" & server & port & "; Uid=" & uname & "; Pwd=" & pword & "; Database=***;"
Try
connection.Open()
MessageBox.Show("Connection Opened Successfully")
Return True
connection.Close()
Catch mysql_error As SqlException
MessageBox.Show("Error Connecting to Database: " & mysql_error.Message)
Return False
Finally
connection.Dispose()
End Try
End Function
If anyone here could help me out in finding the solution as to how I can get onto that MySQL server, you'ld be forever in my debt.
Notes: I'm using VS 2012 express, programming this exclusively in VB.NET, because it's quite a big project (for me) and it's the language I know best. Any add-ons required can be downloaded, as long as other users won't have to download it aswell.
I've never used a MySQL database before, so I might just be doing something completely wrong.
EDIT: The information that is given beforehand contains:
server ip, port, database ID, username & password.

You can't connect to MySQL using SqlConnection class. It is designed to connect to MS SQL Server. Try use this

Found it, this code works perfectly:
Public Function sqlConnect(ByVal server, port, instance, uname, pword) As Boolean
Dim connection As MySqlConnection
connection = New MySqlConnection()
connection.ConnectionString = "Host=" & server & ";port=" & port & _
";user=" & uname & ";password=" & pword & ";"
Try
connection.Open()
MessageBox.Show("Connection Opened Successfully")
Return True
connection.Close()
Catch mysql_error As MySqlException
MessageBox.Show("Error Connecting to Database: " & mysql_error.Message)
Return False
Finally
connection.Dispose()
End Try
End Function

Related

VB.Net with Mysql A connection attempt failed..." error arise when trying to read data from Mysql table. Insert into statement is working

I'm new to Mysql databases. I created and connected successfully a database for the local server. But "A connection attempt failed..." error arise when trying to read data from a table. "Insert into ..." statement is working. I searched for whole web for the reason. Not success. Anyone can help, please. Thank in advance...
Complete error description:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
Relevant Code as follows:
following function Working and Connected successfully
Public Function Connect() As Boolean
Dim Status As Boolean
Try
conn.ConnectionString = "Server=" & Server & ";Port=3306;Database=" & DBName & ";User ID=" & UID & ";Password=" & Pwd & ";CharSet=utf8;"
conn.Open()
cmd.Connection = conn
If conn.State = ConnectionState.Open Then
Status = True
End If
Catch ex As Exception
ErrorMsg = ex.Message
Status = False
End Try
Return Status
End Function
Following Function returns the error...
Public Function getData(ByVal SQLStr As String) As MySql.Data.MySqlClient.MySqlDataReader
Dim tmpDR As MySql.Data.MySqlClient.MySqlDataReader
If conn.State = ConnectionState.Open Then
cmd.CommandText = SQLStr
tmpDR = cmd.ExecuteReader()
Else
MsgBox("Database not connected...", MsgBoxStyle.Exclamation, "Connection Error")
tmpDR = Nothing
End If
getData = tmpDR
End Function
Get rid of any class level database objects. Get rid of the Function Connect altogether. If you ever start to write
If conn.State = ConnectionState.Open Then
you should know you are doing it wrong.
Don't pass DataReader's around. The connection must remain open for them to function. Load a DataTable and pass that after the connection and command are disposed by the Using block.
If you intend to show a message box to the user, let exceptions bubble up to the user interface code.
Private ConStr As String = "Server=" & Server & ";Port=3306;Database=" & DBName & ";User ID=" & UID & ";Password=" & Pwd & ";CharSet=utf8;"
Public Function getData(ByVal SQLStr As String) As DataTable
Dim dt As New DataTable
Using conn As New MySqlConnection(ConStr),
cmd As New MySqlCommand(SQLStr)
conn.Open
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
As you can see, it only takes one simple line to create a connection. Connections are precious resources and should only be opened directly before the .Execute... and closed as soon as possible.

Error connecting to MySQL database (No such host is known)

While using the following code to connect to my SQL database:
MySqlConnection.ConnectionString = "server=vipervenom.net.mysql; userid=vipervenom_net_userinfo; password=PASSGOESHERE; database=vipervenom_net_userinfo;"
it prompts an error saying
Unable to connect to any of the specified MySQL hosts. ---> No such host is known.
I've been looking for hours to find an answer to this, but even though my host and login information is correct, it gives me that error. Take a look at the picture for login information -->
The entire source code:
MySqlConnection = New MySqlConnection
MySqlConnection.ConnectionString = "server=vipervenom.net.mysql; userid=vipervenom_net_userinfo; password=PASS GOES HERE; database=vipervenom_net_userinfo;"
Try
MySqlConnection.Open()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Dim MyAdapter As New MySqlDataAdapter
Dim sqlquery = "SELECT * From Users WHERE email='" & TextBox1.Text & "' AND password='" & TextBox2.Text & "';"
Dim command As New MySqlCommand
command.Connection = MySqlConnection
command.CommandText = sqlquery
MyAdapter.SelectCommand = command
Dim Mydata As MySqlDataReader
Mydata = command.ExecuteReader
If Mydata.HasRows = 0 Then
MsgBox("Wrong login information!")
Else
MsgBox("Login Successful! :D")
End If
Thank you in advance!
For what it's worth, vipervenom.net.mysql is not, and cannot be, a valid hostname, your hosting provider's statements to the contrary notwithstanding.
There aren't any hostnames ending in .mysql because that is not a valid top level domain name.
It's possible your hosting provider has an internal domain naming service handling .mysql as a TLD. But you won't be able to use that hostname from outside their network.
Ask your hosting provider what hostname to use for your MySQL server from outside their network.

MS Access to MySQL Connection

I am building an application, using MS Access as a front-end of a MySQL DB. The application consists of a lot of Forms all of which will execute many different SQL statements.
I am establishing the connection using:
Dim oConn As New ADODB.Connection
Dim Server_Name As String
Dim Database_Name As String
Dim User_ID As String
Dim Password As String
Server_Name = "localhost"
Database_Name = "test"
User_ID = "root"
Password = ""
oConn.Open "DRIVER={MySQL ODBC 5.3 ANSI Driver}" _
& ";SERVER=" & Server_Name _
& ";DATABASE=" & Database_Name _
& ";UID=" & User_ID _
& ";PWD=" & Password _
& ";OPTION=16427"
My questions are:
Is it better to Open and Close the connection each time i run an SQL Statement, or Open the connection, when the Application runs and close when the application closes?
-If the first way is better, Can I Create a global Function that returns a connection, to be used in the current form and not having to write the same code over and over for each form and/or SQL statement?
-If the second way is better, Can I Declare and Open the Connection globally, so It can be used from any form?
Keep in mind that:
-There are 50+ different forms and sub-forms in the application.
-The application should be able to run on multiple computers at once accessing 1 database.
I had this same question and nobody got around to answering it.
In general, its better to keep the connection open when you're going to use it and close it when you're done, but not before then. Which is fine if you use it on a per-form basis but if it gets shared it gets a little more complicated.
What I did initially was open the connection for each form, subforms grabbed the connection from their parent, and the form closes the connection when it gets closed.
The issue, if multiple forms use the same connection, is that if you close that connection, other forms using it will have errors and fail. So, if you want to share the connection between forms you can, but just make sure that it never closes unless the file is being closed. I am currently using this method, since I have a base 'menu' form that can't be closed without closing the file, I close the connection onClose for that form.
Another thing to keep in mind, is that the computer could be randomly disconnected from the server, so any code that requires the connection should have a quick test to re-open the connection if it got closed by accident somehow.
EDIT:
In it's own module.
Public DB_CONNECTION As ADODB.Connection
Function openConnect(ByRef myconn As ADODB.Connection) As Integer
Static retries As Integer
Dim server As String
server = "localhost"
On Error GoTo connectError
myconn.ConnectionTimeout = 10
myconn.Open "DRIVER={MySQL ODBC 5.1 Driver};SERVER=" & server & "DATABASE=data;USER=" & getSQLuser & ";PASSWORD=password;Option=3"
openConnect = 1
retries = 0
Exit Function
connectError:
'retry several times on failure
Dim errADO As ADODB.Error
For Each errADO In myconn.Errors
Debug.Print vbTab & "Error Number: " & errADO.Number
Debug.Print vbTab & "Error Description: " & errADO.Description
Debug.Print vbTab & "Jet Error Number: " & errADO.SQLState
Debug.Print vbTab & "Native Error Number: " & errADO.NativeError
Debug.Print vbTab & "Source: " & errADO.Source
Debug.Print vbTab & "Help Context: " & errADO.HelpContext
Debug.Print vbTab & "Help File: " & errADO.HelpFile
If errADO.Number = -2147467259 Then
If retries < 3 Then
If MsgBox("Connection Error, Try to reconnect or close any connection-enabled forms,check your internet connection and try again.", vbCritical + vbRetryCancel, "Connection Error") = vbRetry Then
retries = retries + 1
Call openConnect(myconn)
Exit Function
End If
Else
MsgBox "Connection error. Retried 3 times, check your internet connection and/or contact your system administrator.", vbCritical + vbOKOnly, "Critical Connection Error"
retries = 0
Exit Function
End If
End If
Next
Select Case err
Case 0
Case Else
MsgBox "Error Code " & err & ", " & Error(err), vbCritical, "Error #" & err
End Select
openConnect = -1
End Function
Function closeConnect()
If Not (DB_CONNECTION Is Nothing) Then
If DB_CONNECTION.State = adStateOpen Then
DB_CONNECTION.Close
End If
End If
End Function
Function tryConnect()
Dim err
If DB_CONNECTION Is Nothing Then
Set DB_CONNECTION = New ADODB.Connection
Call openConnect(DB_CONNECTION)
Else
If Not (DB_CONNECTION.State = adStateOpen) Then
Call openConnect(DB_CONNECTION)
End If
End If
End Function
In my case, I never call openConnect directly, but always call tryConnect onOpen of any forms that use the DB, or before calls that might happen after some time (for example, the save button). If it's already open, no harm done, but if it's not it prevents an error.
closeConnect I call OnError and OnClose of the menu form.

How to find out what database is linked to a certain ID in VB.NET

Basically, I have a VB.NET project with which I connect to a remote MySQL server.
The credentials that I can provide would be "server ip", "port", "database ID", "username" and "password".
Pretty basic stuff, except for the fact that it's the DB ID that's given and not the actual DB name. How can I retrieve the name of the database which is linked to that ID?
Currently I use this connection string to connect to it
connection.ConnectionString = "Host=" & server & ";port=" & port & ";user=" & uname & ";password=" & pword & ";"
Note: The reason I need to be able to have these in variables is because I plan to distribute this tool to some friends of mine, which have a different MySQL server to connect to, with different database names etc. And because not everyone needs to know what the database is called, due to safety reasons.
Edit: Another thing I could do is have my program check every database on the server and return which database has a certain table in it, then use that output for the rest of my program.
I've found a workaround, although this might not be applicable to other MySQL databases.
Here's how I did it:
Public Function sqlConnectTest(ByVal server, port, instance, uname, pword) As Boolean
Dim connection As MySqlConnection
connection = New MySqlConnection()
connection.ConnectionString = "Host=" & server & ";port=" & port & _
";user=" & uname & ";password=" & pword & ";"
Try
connection.Open()
MessageBox.Show("Connection Opened Successfully")
**Dim stm As String = "SELECT TABLE_SCHEMA from information_schema.TABLES where TABLE_NAME like 'survivor'"**
Dim cmd As MySqlCommand = New MySqlCommand(stm, connection)
Dim reader As MySqlDataReader = cmd.ExecuteReader()
While reader.Read()
DBname = reader.GetString(0)
End While
reader.Close()
connection.Close()
Return True
Catch mysql_error As MySqlException
MessageBox.Show("Error Connecting to Database: " & mysql_error.Message)
Return False
Finally
connection.Dispose()
End Try
End Function
Obviously this solution would only work when you have an information_schema database, containing a table which shows all the tables in all the databases on the server.

trying to connect mysql with vb.net

I've found this at connection strings.com
http://connectionstrings.com/mysql
Do I need to download connector-net from this site: http://dev.mysql.com/downloads/connector/net/
I recycled the code that I used in connecting vb.net with ms sql:
Imports system.data.sqlclient
idnum = TextBox1.Text
lname = TextBox2.Text
fname = TextBox3.Text
skul = TextBox4.Text
Using sqlcon As New SqlConnection("Server=localhost;Port=3306;Database=testing;Uid=root;Pwd=mypassword;")
sqlcon.Open()
Dim sqlcom As New SqlCommand()
sqlcom.Connection = sqlcon
sqlcom.CommandText = "INSERT INTO [student](ID, LASTNAME, FIRSTNAME, SCHOOL) VALUES (#ParameterID, #ParameterLastName, #ParameterFirstName, #ParameterSchool)"
sqlcom.Parameters.AddWithValue("#ParameterID", TextBox1.Text)
sqlcom.Parameters.AddWithValue("#ParameterLastName", TextBox2.Text)
sqlcom.Parameters.AddWithValue("#ParameterFirstName", TextBox3.Text)
sqlcom.Parameters.AddWithValue("#ParameterSchool", TextBox4.Text)
sqlcom.ExecuteNonQuery()
End Using
But I get this error:
A network-related or instance-specific
error occurred while establishing a
connection to SQL Server. The server
was not found or was not accessible.
Verify that the instance name is
correct and that SQL Server is
configured to allow remote
connections. (provider: Named Pipes
Provider, error: 40 - Could not open a
connection to SQL Server)
Please help, what solutions would you recommend to this problem?
This article should get you started:
The VB.NET-MySQL Tutorial – Part 3
The article uses MySQL Connector for .NET...
MySQL Connector/NET is available for
download at
http://dev.mysql.com/downloads/connector/net/.
Download the version that includes an
installer to your local hard-drive and
extract the Zip file.
Double-click the installer file to
begin the installation process.
Perform a complete install to the
default directory.
In the code you have:
conn = New MySqlConnection()
conn.ConnectionString = "server=" & txtServer.Text & ";" _
& "user id=" & txtUsername.Text & ";" _
& "password=" & txtPassword.Text & ";" _
& "database=in_out"
Check this out too:
Accessing MySQL Database from my VB.NET 2008 Project