Jonas
Jonas

Reputation: 311

Cannot connect to MySQL database in C#.NET

So I'm following this tutorial: http://support.microsoft.com/kb/314145/

and I get an unexpected error: A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

My class looks like this:

    class Database
{
    public Database()
    {
        string connectionString = "Password=pass;User ID=userid;Initial Catalog=soksko;Data Source=(local)";
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
            Console.WriteLine("State: {0}", connection.State);
        }

        Console.WriteLine("Database: OK");
    }

}

I googled, but I couldnt find anything valuable. I am using MySQL database, it is on the same computer and I am using VS 2013. I successfully added my database to Server Explorer with the same connection information that I use above, but I get exception, when I try to open the connection.

Upvotes: 1

Views: 2380

Answers (3)

therogoman
therogoman

Reputation: 66

SqlConnection is for MS SQL Server. For MySql you need to use a MySqlConnection class provided by the MySQL connector (http://dev.mysql.com/doc/connector-net/en/index.html)

using MySql.Data.MySqlClient;

using(MySqlConnection myConnection = new MySqlConnection(myConnectionString))
{
    myConnection.Open();
    // execute queries, etc
}

Upvotes: 2

David Libido
David Libido

Reputation: 479

The tutorial you're using is for Sql Server, not MySQL.

Upvotes: 0

ebyrob
ebyrob

Reputation: 26

See this link for how a MySQL connection string should look:

ASP.NET use SqlConnection Connect Mysql

See this link for an explanation of the oft mis-used Data Source=(local):

http://blogs.msdn.com/b/sql_protocols/archive/2008/09/19/understanding-data-source-local-in-sql-server-connection-strings.aspx

hint you're not using SQL-Server so it won't work for you

Upvotes: 1

Related Questions