connection string from c# to msql

313 views Asked by At

I am new to msql and i am working on MySQL Workbench 8.0 CE I am trying to bind data from database to datagridview as show below but i am getting error below

but I am able to connecto my database using MySQL Workbench 8.0 CE so the connection to up so what I can do ?

    public void GetPersonData()
    {
        string connstr = "Server=localhost;Database=newsequesterdb;Uid=reser;Pwd=00";
        string query = "SELECT * FROM NEWSEQUESTERDB.PERSON;";

        using (SqlConnection conn = new SqlConnection(connstr))
        {
            using (SqlDataAdapter adapter = new SqlDataAdapter(query, conn))
            {
                DataSet ds = new DataSet();
                adapter.Fill(ds);
                dgv_data.DataSource = ds.Tables[0];
            }
        }
    }

error message

System.Data.SqlClient.SqlException: 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)
2

There are 2 answers

0
D Stanley On

SqlConnection is specific to MS SQL Server. Use MySqlConnection (and associated command and data adapter classes) instead.

Note that MySqlConnection is not built in to the .NET Framework - you'll need to install it separately.

0
fared On

The thing is that you cannot use an SqlConnection instance nor SqlAdapter, those are intended to be SQL Server connection classes. And this you can see by the exception itself.

...(provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

So, what's next? You should really look up to this question and may solve a few doubts.

From that question we can see that is using other references to connect to MySQL. Specifically Oracle's nugget package: MySQL.Data

using MySql.Data;

using MySql.Data.MySqlClient;

From that question example:

var dbCon = DBConnection.Instance();
dbCon.DatabaseName = "YourDatabase";
if (dbCon.IsConnect())
{
    //suppose col0 and col1 are defined as VARCHAR in the DB
    string query = "SELECT col0,col1 FROM YourTable";
    var cmd = new MySqlCommand(query, dbCon.Connection);
    var reader = cmd.ExecuteReader();
    while(reader.Read())
    {
        string someStringFromColumnZero = reader.GetString(0);
        string someStringFromColumnOne = reader.GetString(1);
        Console.WriteLine(someStringFromColumnZero + "," + someStringFromColumnOne);
    }
    dbCon.Close();
}