1、首先得到MySql官网下载连接所需的.net的文件,文件下载地址为点击打开链接,下载平台选择.Net&Mono,下载ZIP免安装版;也可以到这边下载:CSDN免积分下载,如下图:
2、解压缩下载下来的文件,得到:
其中v4里面的文件为:
3、把上面四个.dll文件添加到C#项目的引用中。
选中这四个文件,添加。
4、测试连接
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string connstr = "server=localhost;User Id=root;password=123;Database=d_test;port=3306";
String sqlSearch = "select * from t_people";
MySqlConnection mycon = new MySqlConnection(connstr);
MySqlCommand mySqlCommand = getSqlCommand(sqlSearch, mycon);
mycon.Open();
getResultset(mySqlCommand);
Console.ReadLine();
mycon.Close();
}
/// <summary>
/// 查询并获得结果集并遍历
/// </summary>
/// <param name="mySqlCommand"></param>
public static void getResultset(MySqlCommand mySqlCommand)
{
MySqlDataReader reader = mySqlCommand.ExecuteReader();
try
{
while (reader.Read())
{
if (reader.HasRows)
{
Console.WriteLine("编号:" + reader.GetString(0) + "|姓名:" + reader.GetString(1) + "|年龄:" + reader.GetString(2) + "|学历:" + reader.GetString(3));
}
}
}
catch (Exception)
{
Console.WriteLine("查询失败了!");
}
finally
{
reader.Close();
}
}
/// <summary>
/// 建立执行命令语句对象
/// </summary>
/// <param name="sql"></param>
/// <param name="mysql"></param>
/// <returns></returns>
public static MySqlCommand getSqlCommand(String sql, MySqlConnection mysql)
{
MySqlCommand mySqlCommand = new MySqlCommand(sql, mysql);
return mySqlCommand;
}
}
}