1、先自安装好vs2015、Mysql;
再安装好以下的(.msi);解压好(.zip)文件。可在微软官网下载,链接:https://dev.mysql.com/downloads/connector/net/
(.msi)文件不确定是否需要安装,可以先不安装。
2、(1)打开解决方案:工具——连接数据库——填写完连接Mysql的信息——测试连接——如果显示连接成功,即点击确认即可。此时连接成功建立。
(2)解压(.zip)文件,在项目中引用里面的(.dll)文件。为了稳定起见,我们直接引用里面所有的dll文件。
其中,
using System.Data:DataSet
using MySql.Data.MySqlClient:MySqlConnection conn、 MySqlDataAdapter
3、最后在项目中的代码实现:(为可实现的源代码,请根据自身要求修改)
#region 数据库总调度
//数据库连接
private DataSet dsall;
private static String mysqlcon =
"Database=imserver;Data Source=localhost;User id=root;password=123456;charset=utf8;port=3306";
//数据库连接信息
private MySqlConnection conn;
private MySqlDataAdapter mDataAdapter;
/// <summary>
/// 与Mysql数据库建立连接,并根据语句获取数据
/// </summary>
/// <param name="ask">SQL语句</param>
/// <returns></returns>
public DataTable GetTable(string ask)
{
dsall = new DataSet();
//DataTable hard = new DataTable();
conn = new MySqlConnection(mysqlcon);
conn.Open();
if (conn != null)
{
try
{
mDataAdapter = new MySqlDataAdapter(ask, conn);
mDataAdapter.Fill(dsall, "dsall");//取到数据存于dsall
//hard.Rows[0]["clientName"].ToString();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return dsall.Tables[0];
}
#endregion
#region 方法实现数据库
/// <summary>
/// 获取用户数据
/// </summary>
/// <param name="cId">用户id</param>
/// <returns></returns>
public List<Client> GetClientMessage()
{
//定义List<Client>,确定sql语句,去数据库中获取数据,返回存于list中
List<Client> client_list = new List<Client>();
string sqlstr = "select * from client";
DataTable table = GetTable(sqlstr);
for (int i = 0; i < table.Rows.Count; i++)
{
Client temp = new Client();
//hard.Rows[0]["clientName"].ToString();
temp.clientName = table.Rows[i]["clientName"].ToString();
temp.clientId = long.Parse(table.Rows[i]["clientId"].ToString());
temp.telephone = long.Parse(table.Rows[i]["telephone"].ToString());
temp.sign = table.Rows[i]["sign"].ToString();
temp.address = table.Rows[i]["address"].ToString();
temp.clientImage = table.Rows[i]["image"].ToString();
temp.passWord = table.Rows[i]["passWord"].ToString();
temp.state = table.Rows[i]["state"].ToString();
temp.gender = table.Rows[i]["gender"].ToString();
client_list.Add(temp);
}
return client_list;
}
#endregion