-2

What should I do to connect to MySql?

string constr = "Data Source=steve-pc;Initial Catalog=itcast2014;Integrated Security=True";

using (SqlConnection con = new SqlConnection(constr))
{
    string sql = "select count(*) from TblPerson";

    using (SqlCommand cmd = new SqlCommand(sql, con))
    {
        con.Open();

        //object count = (int)cmd.ExecuteScalar();

        object count = Convert.ToInt32(cmd.ExecuteScalar());
        Console.WriteLine("TblPerson表中共有{0}条数据。", count);
    }
}
GSerg
  • 76,472
  • 17
  • 159
  • 346

2 Answers2

0

Install Oracle's MySql.Data NuGet package, to add it as a package and it is the easiest way to do. You don't need anything else to work with MySQL database.

Or you can run below command in Package Manager Console

PM> Install-Package MySql.Data

and this answer could help you: How to connect to MySQL Database?

Roxana Sh
  • 294
  • 1
  • 3
  • 14
0

You will have to install package for mysql data. Once you have that installed and added references, you can do it like this :

string server = "steve-pc";
string database = "itcast2014";
string username = "YourMysqlUsername";
string password = "YourMysqlPassword";
string connstring = string.Format("Server={0}; database={1}; UID={2}; password={3}",server, database, username, password);


using(var connection = new MySqlConnection(connstring);
{  
    connection.Open();

    string query = "select count(*) from TblPerson";
    var cmd = new MySqlCommand(query, dbCon.Connection);
    var reader = cmd.ExecuteReader();
    while(reader.Read())
    {
        string personsCount = reader.GetString(0);
        Console.WriteLine(personsCount);
    }
    connection.Close();
}

More detailed and better answer for this is on How to connect to MySQL Database?

Vytautas Plečkaitis
  • 851
  • 1
  • 13
  • 19