Rajesh Nadar
Rajesh Nadar

Reputation: 27

Unable to connect to MySql Server in Visual C#

I am trying to create a local database using MySql in Visual C# but connection is not getting established in the code but when i add the server in the server explorer under data connections its working. I tried test connection it says connection succeeded but its not working in the code.

string connStr = "server=localhost;user=root;database=entry_database;password=superadmin";
con = new SqlConnection(connStr);

This throws an error saying

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)

Upvotes: 1

Views: 1565

Answers (3)

Vikas Goyal
Vikas Goyal

Reputation: 457

Correct, the format used by you to create the connection string is incorrect, giving you the error you mentioned above.

Actually, the way the connection string is written in MS-SQL is very different from MY-SQL. Every database has its own way of connecting and its individual connection tags:-

Please find the list of connection details for MS_SQL below. This would help you not only in the current mentioned scenario but also will provide a reference for future changes:-

https://www.connectionstrings.com/mysql/

Upvotes: 0

Bradley Grainger
Bradley Grainger

Reputation: 28162

You cannot use the SqlConnection class to connect to a MySQL server; that is for Microsoft SQL Server only.

Instead, install the MySqlConnector NuGet package and use the following code:

string connStr = "server=localhost;user=root;database=entry_database;password=superadmin";
using (var con = new MySqlConnection(connStr))
{
    // ...
}

Upvotes: 1

Leandro Bianch
Leandro Bianch

Reputation: 92

Your connection string is wrong.. change keys "user" to "Uid" and "password" to "Pwd".

follow eg:

string connStr = "server=localhost;Uid=root;database=entry_database;Pwd=superadmin";

con = new SqlConnection(connStr);

Upvotes: 0

Related Questions