我该怎么做才能连接到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);
}
}
答案 0 :(得分:0)
安装Oracle的MySql.Data NuGet软件包,将其添加为软件包,这是最简单的方法。您无需其他任何操作即可使用MySQL数据库。
或者您可以在Package Manager控制台中运行以下命令
PM> Install-Package MySql.Data
此答案可以帮助您:How to connect to MySQL Database?
答案 1 :(得分:0)
您将必须安装mysql数据包。一旦安装并添加了引用,就可以这样:
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();
}
对此更详细,更好的答案在How to connect to MySQL Database?