MySQL connection string refused connection - mysql

I have installed MySQL Community server on local machine and am trying to access it from .NET Core API. Something must be wrong with either the connection string or the server configurations. I have checked the server configs to make sure TCP/IP connections are allowed, checked the connection string according to tutorials but still fail to connect, getting this exception in code:
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.
Tried connecting to MSSQL database and there are no issues, so nothing else could be wrong from code-side apart from the connection string itself.
The connection string:
"SqlConnectionString": "Server=127.0.0.1;Uid=admin;Pwd=admin;Database=sys;"
SQL query in code (using Dapper):
private const string SQL_INSERT_ENTITY = #"
INSERT INTO [sys].[adminportal_restapi] (Id, FeatureName, IsEnabled, LastInsertUpdate)
VALUES (#Id, #FeatureName, #IsEnabled, #LastInsertUpdate)
";
Database layout:

Found the solution - you have to use a different connector.
Basically these changes are needed:
in project.json add this dependency: "MySql.Data.Core": "7.0.4-IR-191"
and in code change new SqlConnection to new MySqlConnection
EDIT: that package got unlisted by MySQL devs without releasing a newer version (which is a complete douchebag move, IMO), so just use this one instead: "MySqlConnector": "0.11.5" syntax for connections is identical, just it doesn't support integrated security, which might suck in some cases. Good luck

Related

AppHarbor: Connecting to a MySQL DB via ASP.NET MVC 5 + Dapper

I'm trying to get an application up and running on AppHarbor. It's been smooth sailing for the most part, but today I'm having trouble connecting to my MySQL database.
Using the credentials AppHarbor provided me with, I successfully connected to the mySQL database instance using dbForge Studio Express, created the necessary SQL schema, and populated the tables with data. Now I'm trying to use the following C# code to do a simple query using Dapper:
var sqlConnStringBuilder = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["AppHarborMySql"].ConnectionString);
using (var db = new SqlConnection(sqlConnStringBuilder.ConnectionString))
{
db.Open();
// Do database query stuff
return result;
}
But this is the error that I'm running into, when I try to open the database connection:
An exception of type 'System.Data.SqlClient.SqlException' occurred in
System.Data.dll but was not handled in user code
Additional information: 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)
This is how I've declared the connection string in Web.config:
<connectionStrings>
<add name="AppHarborMySql" connectionString="server=MYDOMAIN.mysql.sequelizer.com;database=MYDBNAME;uid=MYUSERNAME;pwd=MYPASSWORD" providerName="System.Data.SqlClient" />
</connectionStrings>
Am I missing something obvious? I'm using ASP.NET MVC 5.x and the latest version of Dapper... thanks in advance!
And of course, despite having spent the better part of an hour investigating, I discover the answer immediately after posting the question.
For anyone else who may run across the same problem: I added the MySql.Web NuGet package to my MVC project, added using MySql.Data.MySqlClient; to the top of my page, and then changed my code to point from SqlConnection to MySqlConnection. Here's what my working code block now looks like:
using (var db = new MySqlConnection(ConfigurationManager.ConnectionStrings["AppHarborMySql"].ConnectionString))
{
db.Open();
// Do database query stuff
return result;
}

MySQL Fabric failover and Connection Pooling with Hibernate

I'm attempting to implement automatic failover via a MySQL Fabric Server Group using a JNDI Resource, Hibernate, and Connection Pooling. Our DB farm is properly setup with MySQL Fabric and I'm attempting to implement the client/connector.
I have a JNDI resource declared in my server.xml file which has a MySQL Fabric-based URL and Driver, and uses connection pooling with hibernate.
<Resource
name="jdbc/myApp"
type="javax.sql.DataSource"
driverClassName="com.mysql.fabric.jdbc.FabricMySQLDriver"
maxWait="1000"
url="proper.fabric.url/fabricServerGroup=myFabricGroup"
maxActive="45"
validationQuery="select 1 from dual"
/>
The problem I'm having is that the connection pooling and Fabric do not play well together. After taking down the master DB, Fabric automatically promotes a slave as expected. However, when I attempt to make a new connection to the DB I'm getting old now-defunct connections back, most notably I'm getting a read-only connection back when I'm requesting readwrite. As additional info if I restart my Tomcat server and ask for a fresh connection I get the correct results. The problem I'm having specifically occurs because of connection pooling.
What I need to know is if there's a key/value pair which I'm missing that would make my FabricDriver smart enough to know to wipe the connection pool when automatic failover occurs.
The best I've found is to use testOnBorrow, which unfortunately can only use a SELECT query (via validationQuery), which still succeeds when I'm getting a read-only connection back despite asking for readwrite.
Has anybody solved this issue before?
Note: If I attempt to use com.mysql.fabric.jdbc.FabricMySQLDataSource I can't even successfully make any connections. The regular javax.sql.DataSource seems to be the correct value here.
Second Note: I'm using mysql-connector-java version 5.1.35
Just heard back from Oracle, this is apparently a known bug and is going to be fixed in the upcoming release: 5.1.36
I have the same issue with Oracle MySQL Connector/J 5.1.39.
I am able to follow the failover requesting a new connection to Fabric only catching the Exception in my code:
...
} catch(java.sql.SQLException e) {
int errorCode = e.getErrorCode();
/*
* java.sql.SQLException: The MySQL server is running with the --read-only option so it cannot execute this statement
* java.sql.SQLException: Cannot execute statement in a READ ONLY transaction.
*
*/
if(errorCode == 1290 || errorCode == 1792) {
System.out.println("Failover");
System.out.println(e.toString());
connection.close();
rawConnection = DriverManager.getConnection(baseUrl, mysql_user, mysql_password);
connection = (FabricMySQLConnection) rawConnection;
}
Asking Oracle support about the automatic failover from the connector side they answer "Connector/J doesn't have desired feature".
There is someone able to integrate that catching inside the connection pool?

Connecting to a MySQL DB from a WPF app

I have been trying to connect a C# WPF app with a MySQL database. The database is on a Linux machine in my network. I have a lot of experience connecting with PHP but have never done it with a .NET product. I have read through everything I have found online. I have already downloaded and installed the MySQL connect stuff and attached it to the project. I have gone into the db and made sure it would accept queries from my work PC using phpMyAdmin. I have tried a wide variety of code to call the DB. I have changed the order of everything in connStr. I have changed the labels and formatting to try everything I have come across. I am able to connect to the DB with all of the web based tools that tie to this app so I know that I have the right info. I have never posted on here so I am sorry about the formatting. Everything I have read make this sound quite straightforward. I and am currently using this:
string connStr = "user=admin;database=test;server=192.168.0.37;password=******;"; MySqlConnection conn = new MySqlConnection(connStr);
try
{
Console.WriteLine("Trying to connect to: ..." + connStr); Console.WriteLine("Connecting to MySQL...");
conn.Open();
// Perform database operations
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
conn.Close();
Console.WriteLine("Done.");
and I am getting this error:
Test.vshost.exe Error: 0 : Unable to connect to any of the specified MySQL hosts.
A first chance exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
MySql.Data.MySqlClient.MySqlException (0x80004005): Unable to connect to any of the specified MySQL hosts.
at MySql.Data.MySqlClient.NativeDriver.Open()...
Thank you for your help on this!
When you are trying to contact a server in a home network using a basic modem/router, it can fail to recognize or pass along the port number you sent. In this case it was not recognizing or sending 3306 (default for mysql). This would make it so it would never work without SSH tunneling. After adding SSH tunneling it worked as advertised.

Why does SSIS connection works with Windows but not with SQL Server authentication?

I have an SSIS package that contains a Lookup Transformation. This requires a connection to the database. At the connection manager, when I use the Windows authentication the connection works fine but when I use SQL Server Authentication then I get this error:
[A140_DAMAGETYPETEXT [3799]] Error: SSIS Error Code DTS_E_CANNOTACQUIRECONNECTIONFROMCONNECTIONMANAGER. The AcquireConnection method call to the connection manager "servername.Datenbankname.sqlUser" failed with error code 0xC0202009. There may be error messages posted before this with more information on why the AcquireConnection method call failed.
Connection string:
Data Source=TheServerName;User ID=TheSQLUser;Initial Catalog=TheDababase;Provider=SQLNCLI10.1;Persist Security Info=True;Application Name=NameOfThePackage{80F4BFAB-642D-457E-9F47-1E811AFA48D0}ServerName.TheDababas‌​e.TheSQLUser;
Cause of the issue:
Your connection string is missing the Password attribute. That is the reason why the connection manager is failing to connect to the database instance.
Possible option to fix:
When you create the connection manager on SSIS, make sure to check the Save my password box so that the Password is retained in the connection string. If you do not check this box, the value will not be retained and you have to key in the value.
Package configuration:
If you are using package configurations, adding / updating the connection manager will cause the Password attribute to drop from the connection string property. I usually use database based package configuration. So, I use a query to update the connection string in the package configuration table every time I update the package configurations.
Recommendation:
I prefer to use Windows authentication so that the password to connect to the database is not exposed. I feel that Windows Authentication is little more secure than dealing with SQL Server Authentication.
here was the solution for me: click
the thread from Raj_007 was the rescue. I use a sequece container and the TransactionOption was setting to required.
I changed the TransactionOption to supported and it worked for me.

Unable to connect to SQL Server using SqlConnection (but OK with OleDbConnection)

I have a SQL Server 2008 instance running on Amazon RDS and another test database server running as a SQL 2008 Express installation on an Amazon EC2 instance.
I am able to connect to both of these servers using SQL Server Management Studio (and other tools like Navicat) so, I am happy that the servers are correctly configured to accept remote TCP connections and that there are no firewall issues.
However, when I try to establish a connection from a C# application, using SqlConnection, it fails with a timeout. But, if I try the same experiment using an OleDbConnection it works fine (after adjusting the connection string to include the provider information).
For comparison, if I run the experiment on the EC2 instance, using an SqlConnection with a connection string that establishes a (local) connection, it also works correctly, so I assume the issue is related to the use of SqlConnection remotely.
Does anyone have any idea what I need to do to get SqlConnection working, or what steps I could take to further diagnose the cause of the problem?
Many thanks for your advice,
Tim
Apparently this behavior is caused by this issue and, in my case, it was specifically because my PCTools firewall was doing something unexpected with the outbound TCP packets created by SqlConnection.
I implemented a temporary workaround by uninstalling PCTools (it was not sufficient to merely disable the firewall), so I now have to find a new firewall that complies with what Windows/SQL Client is expecting.