amish
amish

Reputation: 355

Connecting MySQL database with Visual Studio

I made a MySQL server database file from server explorer using the following code to connect the MySQL database:

private void DataAdd_Load(object sender, EventArgs e)
{
    try
    {
        var conn = new MySqlConnection();
        conn.ConnectionString =
             "Data Source=(LocalDB)\\MSSQLLocalDB;" +
             "User Instance=true;" +
             "Integrated Security=false;" +
             "AttachDbFilename=C:\\Path\\filename.MDF;";
          conn.Open();

        MessageBox.Show("Connected to database");
    }
    catch (Exception e1)
    {
        MessageBox.Show("Connection failed");
    }
}

But the connection always fails.

The error that I found while debugging:

Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll ("The user instance login flag is not allowed when connecting to a user instance of SQL Server. The connection will be closed.")

Upvotes: 0

Views: 2851

Answers (2)

gakker
gakker

Reputation: 13

You will need to use MySQLConnection as answered here:

ASP.NET use SqlConnection connect MySQL

The MySQL connection library might not be included in your solution, so you will need to download it. And change var conn = new SqlConnection(); to:

var conn = new MySqlConnection();

Upvotes: 0

user6522773
user6522773

Reputation:

To connect to MySQL, you need MySqlConnection and a proper MySQL connection string:

private void DataAdd_Load(object sender, EventArgs e)
{
    try
    {
        var conn = new MySqlConnection(@"Server=192.168.1.10;Database=myDB;Uid=myUsername;Pwd=myPassword;");
        conn.Open();
        MessageBox.Show("Connected to database");
    }
    catch (Exception e1)
    {
        MessageBox.Show("Connection failed");
    }
}

Upvotes: 1

Related Questions