网上大部分的教程是从代码开始的,其实第一步要添加MySql.Data.dll到引用文件夹中,添加方法有两种,第一种方法下载MySql.Data.dll(https://pan.baidu.com/s/1bTdk9DPnED8-8wwGvx0Saw,提取密码:ncmu),然后下载到指定文件夹。在VS2017(我用的是)解决方案文件夹中如下操作:
右击鼠标键->添加引用->浏览,然后搜索本机的MySql.Data.dll文件
第二种是:在解决方案中右击鼠标->管理NuNet程序包->在浏览中搜索MySql.Data.dll,然后在线下载安装
然后就可以添加use MySql.Data.MySqlClient;就可以操作MySql数据库了
具体操作如下代码:
using System;
using System.Data;
using MySql.Data.MySqlClient;
namespace Connection_MySql
{
class Program
{
static void Main(string[] args)
{
String connetStr = "server = 127.0.0.1; port = 3306; user = root; password = 360412abc; database = my_student;";
MySqlConnection conn = new MySqlConnection(connetStr);
try
{
conn.Open();
Console.WriteLine("已经建立连接");
string sql = "select *from student_one";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader reader = cmd.ExecuteReader();
//Console.WriteLine(reader.GetString("name") + " " + reader.GetString("number") + " " + reader.GetInt16("age"));
while (reader.Read())
{
Console.WriteLine(reader.GetString("name") + " " + reader.GetString("number") + " " + reader.GetInt16("age"));
}
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
Console.WriteLine("Cannot connect to server, Contact administrator");
break;
case 1045:
Console.WriteLine("Invalid username/password, please try again");
break;
}
}
finally
{
conn.Close();
}
Console.ReadKey();
}
}
}
好啦!C#VS2017可以连接MySql数据库了。