一、ORM简介
对象关系映射(Object Relational Mapping,简称ORM)模式是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术。
以上是官话,个人理解:
1、解决问题:数据库的访问
2、如何解决:数据库由表、记录 组成 -》 把表映射成面向对象的类 ,记录则是对象!
3、两个方面:解决数据描述(所谓的POJO或者实体类)和数据CURD操作;
ASP.NET的解决方案有 Entity Framework (EF)等,初学者可以暂时避开,就从问题着手解决数据库访问问题:把表变成类,对类生成的对象来 -》 实现数据库增删查改操作
二、最简单的MYSQL访问实例
1、打开前面创建的MVC 4.0工程(如没有,重新创建一个,记得添加Controller和Index的视图);
2、在Models里(其实可以在其他任意目录)添加类:

添加一个静态string 字符串连接字段
public static string SqlserverConnectStr = "server=127.0.0.1;charset=utf8;user id=root;persistsecurityinfo=True;database=test;Password=XXXXXXXXX";
Mysql连接字段,server表明MYSQL安装的主机IP,user id 和 Password 分别是Mysql数据库的用户名和密码 ,database 是数据库名
添加一个静态Query 返回 DataSet (数据集,查询集)------访问数据库返回满足需要的数据集合。
public static DataSet Query(string SQLString)
{
using (MySqlConnection connection = new MySqlConnection(SqlserverConnectStr))
{
DataSet ds = new DataSet();
try
{
connection.Open();
MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection);
command.Fill(ds, "ds");
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
}
问题:
1、DataSet未定义
在小齿轮上点击添加对应的引用(或者手动添加):

2、MySqlConnection 则需要添加引用:
右键添加引用,选择添加引用:

点击浏览,选择MYSQL的DLL

添加到工程:
在类中,添加引用:

测试:
在MYSQL中新建test数据库,并添加表:

其中表结构和测试数据如下:

在Home控制器中的Index action中添加代码:

下断点(F9)

F5进入调试-》 WEB默认路由为 home/index 所以自动进入index的Action
F10 执行到下一步,在监视中,添加对set的监视:

说明:
1、Query函数执行的select 语句是数据库的SQL(结构化查询语言)的命令;本例中是查找user表中所有的数据 select * from user
2、执行查询语句返回是一个数据集合(DataSet),可能包含多张数据表(Tables),本例看第一张表的数据(Tables[0]),数据表有很多行 Rows ,监视窗口看的第一行;
3、每一行数据就是一条记录,记录有很多属性,所有再展开 ItemArray 数组,可以看到第一条记录的每个字段的值
4、可以使用字段名作为索引来查看数据,如下:

综上:数据库的访问并不难,别被所谓的OMR计算吓到了!最简单的数据库访问可以很简单解决这个问题!