Connection.Open() Error: MySqlConnector.MySqlException: 'Unable to connect to any of the specified MySQL hosts.'
I've already tried multiples times with many codes here in Stack, but i still receiveing this error,it's using a jumpbox to connect into a ec2, if i change the string connection to localhost, i get the local database, not the production,some people had said to do that, using the forwardPort but it didn't solve.
links that i've tried:
Connection to MySQL from .NET using SSH.NET Library
How to connect to mysql from C# over SSH
How to forward ports over an SSH tunnel using Granados with C#
and others.
static bool isFirstTimeSSH()
{
Console.WriteLine("Verificando se é a primeira vez \n");
string _privateKeyPath = @"MyKeyPath";
string _privateKeyPassPhrase = "";
string _host = "MyDbHost";
var privateKeyStream = new PrivateKeyFile(_privateKeyPath, _privateKeyPassPhrase);
var sshHostAddress = _host;
var sshPort = 22;
var sshUser = "MyUserSSH";
var ci = new PrivateKeyConnectionInfo(sshHostAddress, port: Convert.ToInt32(sshPort), username: sshUser, privateKeyStream);
using (var client = new SshClient(ci)) // establishing ssh connection to server where MySql is hosted
{
client.Connect();
if (client.IsConnected)
{
var portForwarded = new ForwardedPortLocal("127.0.0.1","MyDbHost", 3306);
client.AddForwardedPort(portForwarded);
portForwarded.Start();
Console.WriteLine("Verificando se é a primeira vez \n");
string mySQLConnectionString = ConfigurationManager.AppSettings.Get("MySQLConnectionString");
string connStr =
string.Format(
"Server = {0};Port = {1};Database = database;Uid = MyDbUser;Pwd = MyDbPass;SslMode=none;default command timeout=10;Connection Timeout=3;MinimumPoolSize=20;maximumpoolsize=500",
portForwarded.BoundHost, portForwarded.BoundPort);
//Aqui você substitui pelos seus dados
var connection = new MySqlConnection(mySQLConnectionString);
var command = connection.CreateCommand();
DataTable dt = new DataTable();
try
{
connection.Open();
command.CommandText = "SELECT count(*) FROM transactions;";
MySqlDataReader dataReader = command.ExecuteReader();
dt.Load(dataReader);
int numberOfTransactions = 0;
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
numberOfTransactions = Convert.ToInt32(reader[0]);
}
}
if (numberOfTransactions < 20)
{
return true;
}
else
{
return false;
}
}
finally
{
if (connection.State == ConnectionState.Open)
connection.Close();
client.Disconnect();
}
}
else
{
Console.WriteLine("Client cannot be reached...");
}
}