I have .NET application which connects mysql database at backend. Following is my code and MySQL connection string use for development.
Code:
Imports MySql.Data.MySqlClient
Module SQLConn
' Global variables declaration
Public ServerMySQL As String
Public PortMySQL As String
Public UserNameMySQL As String
Public PwdMySQL As String
Public DBNameMySQL As String
Public conn As New MySqlConnection
Public sqL As String
'/ Connection DB Public Module
'/ -------------------------------------------------
Public Sub ConnDB()
conn.Close()
getData()
Try
conn.ConnectionString = "Server = '" & ServerMySQL & "'; " _
& "Port = '" & PortMySQL & "'; " _
& "Database = '" & DBNameMySQL & "'; " _
& "uid = '" & UserNameMySQL & "'; " _
& "pwd = '" & PwdMySQL & "'"
conn.Open()
Catch ex As Exception
MsgBox("The system failed to establish a connection", MsgBoxStyle.Information, "Database Settings")
End Try
End Sub
' / Load Application Settings
' / -------------------------------------------------
Sub getData()
Dim AppName As String = Application.ProductName
Try
DBNameMySQL = GetSetting(AppName, "DBSection", "DB_Name", "ax_db")
ServerMySQL = GetSetting(AppName, "DBSection", "DB_IP", "localhost")
PortMySQL = GetSetting(AppName, "DBSection", "DB_Port", "3306")
UserNameMySQL = GetSetting(AppName, "DBSection", "DB_User", "root")
PwdMySQL = GetSetting(AppName, "DBSection", "DB_Password", "xxxxx")
Catch ex As Exception
MsgBox("System registry was not established, you can set/save " &
"these settings by pressing F1", MsgBoxStyle.Information)
End Try
End Sub
This is working pretty fine with early MySQL Community Versions 5.5.3 or similar. Application was running perfectly fine. I want to upgrade MySQL to include more multi-lingual features to my app. I have upgraded to MySQL Community version 8.0.30 and server is running
it gives me an error "connection must be valid and opened".
I tried simple connection string ("server=localhost;uid=root;pwd=xxxxx;database=ax_db") and some other suggestions made in other posts here in www.stackoverflow.com as ("server=localhost;port=3306;user id=roote;pwd=xxxxx;database=ax_db").
Tried even by adding "Persist Security Info=False; Convert Zero Datetime=True" to the connection string. but no luck. app keeps on throws same error.
Here is my Developer Environment
MySQL Connector/NET installed
Windows 10
.NET Framework 4.7.2
Visual Studio 2019
MySQL Community Server 8.0.30
MySQL Workbench 8
Related
I wanted to connect an excel file with a MySQL server for a project, so I searched the internet for a solution. I found some, but all of it was old and I don't prefer 8–10-year-old methods and drivers.
All I got is [Microsoft][ODBC Driver Manager] Data source name not found, and no default driver specified
So, I setted up the following setup:
A MySQL 8.0 server (on a Ubuntu server in the oracle cloud) 64-bit, ODBC connector 8.0 Unicode 64-bit
Office 365 64 bit
I tried to make a connection with some of the methods, but they gave all the same error:
[Microsoft][ODBC Driver Manager] Data source name not found, and no default driver specified
Public Function OpenConnection() As ADODB.Connection
''This function requires the "Microsoft ActiveX Data Objects" Library (Choose v2.8 from references for compatibility across Office versions)
Dim source As String, location As String, user As String, password As String
location = My server IP
user = "ExcelTest"
password = "Pass"
database = "Test"
mysql_driver = "MySQL ODBC 8.0 Driver" ''Tried "MySQL ODBC 8.0 Unicode Driver" too
''Build the connection string
Dim connectionString As String
connectionString = "Driver={" & mysql_driver & "};Server=" & location & ";Database=" & database & ";UID=" & user & ";PWD=" & password
''Create and open a new connection
Set OpenConnection = New ADODB.Connection
OpenConnection.CursorLocation = adUseClient
Call OpenConnection.Open(connectionString)
End Function
Usually I found a pretty good tutorial or walkthrou but this time nothing up to date.
I yes. I am pretty sure All the things are 64 bit.
I do not know where to search Please help
Test the driver has installed correctly by using Windows ODBC Data Source Administrator first.
Option Explicit
Sub test()
Dim conn
Set conn = OpenConnection()
With conn
.CursorLocation = adUseClient
MsgBox "Connected to " & .DefaultDatabase, vbInformation
End With
End Sub
Public Function OpenConnection() As ADODB.Connection
Const location = ""
Const user = ""
Const password = ""
Const database = "test"
Const mysql_driver = "MySQL ODBC 8.0 Unicode Driver"
' Build the connection string
Dim s As String
s = "Driver={" & mysql_driver & "};Server=" & _
location & ";Database=" & _
database & ";UID=" & _
user & ";PWD=" & password
Debug.Print s
' Open connection
Set OpenConnection = New ADODB.Connection
OpenConnection.Open s
End Function
Ok, i don't know if it will be useful but i want to share. Modos and admin will delete if they want.
I'm developping a VB application (actually, i migrate one from Excel VBA) to interact with MySQL Database.
I use VS 2019 16.8.2, Windows 7 x64.
I got a cryptic issue during connection to the database (using ADO, reference used: MS ADO 2.6).
Here's the code:
Public Sub test_connect()
Dim server_name As String
Dim database_name As String
Dim login_database As String
Dim port_number As String
Dim pwd_database As String
server_name = "my_server"
database_name = "my_database"
login_database = "whoisyourdaddy"
pwd_database = "youare"
connexion_dlweb_doc = New ADODB.Connection With {
.ConnectionString = "DRIVER={MySQL ODBC 8.0 ANSI Driver};" _
& "SERVER=" & server_name & "; " _
& "PORT=" & port_number & "; " _
& "DATABASE=" & database_name & "; " _
& "UID=" & login_database & "; " _
& "PWD=" & pwd_database & "; " _
& "OPTION=3"
}
If connexion_dlweb_doc.State <> adStateOpen Then
connexion_dlweb_doc.Open()
End If
End Sub
So, i got an exception with the " connexion_dlweb_doc = New ADODB.Connection" command. It's where it becomes cryptic:
System.TypeInitializationException : 'The type initializer for 'MyAPP.mod_declaration_variables' threw an exception.'
COMException : Retrieving the COM class factory for component with CLSID {00020819-0000-0000-C000-000000000046} failed due to the following error: 80040154 Classe non enregistrée (0x80040154 (REGDB_E_CLASSNOTREG)).
mod_declaration_variables is a module where i declare global variables like connexion_dlweb_doc:
Public connexion_dlweb_doc As ADODB.Connection
So, i asked my best friend google about this cryptic message and the CLSID {00020819-0000-0000-C000-000000000046} refer to...Microsoft.Interop.Excel 14.0.0.0
I use the reference MS Excel Objet Library 14.0 in my project. How did this interact with the ADO connection part? What's the link? Why the code crash here and not before?
I don't know why but the solution was to delete (or comment) every variable declaration using Excel library, e.g:
Public xlApp_arbo_wiki As Excel.Application
Guess it would help noobs like me.
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.
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
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